---
id: 355
lang: en
translation_of: index.md
source_sha256: 3b84b8f140cf47072ea3c923ff29a907c9b324890113e11cf23f38133aee1953
title: "CH2601: Circuit Repair — Solution"
description: "To make a reasonable optimization, we can use a deque, process edges of weight 0 first, and just make sure each point is visited only once."
tags: ["OI","BFS","Bidirectional BFS"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "The inline formula \\(A(x_1,y_1)到B(x_2,y_2)\\) contains the Chinese character 到 (“to”) inside the math delimiters in the source; the TeX was kept verbatim, so 到 still appears in the English text."
  - "电路时符合走向的 reads as a typo for 电路是符合走向的 (“the circuit matches the direction”); translated that way."
---

## Approach

We can think of the whole circuit system as an undirected graph: if going from point $A(x_1,y_1)到B(x_2,y_2)$, the circuit in the cell along this path matches the direction, then we take the edge weight of this path to be $0$; if it goes against the direction, the edge weight is $1$. To make a reasonable optimization, we can use a deque, process edges of weight $0$ first, and then just make sure each point is visited only once. The complexity is fairly low; just look at the code.

<!--more-->

```cpp
// CH2601.cpp
#include <iostream>
#include <cstdio>
#include <vector>
#include <queue>
#include <cstring>
#define pr pair<int, int>
#define ppr pair<int, pr>
using namespace std;
const int maxn = 510, dx[4] = {-1, -1, 1, 1}, dy[4] = {-1, 1, 1, -1}, INF = 0x3f3f3f3f;
const char sym[4] = {'\\', '/', '\\', '/'};
int T, N, M, dist[maxn][maxn];
char map[maxn][maxn];
bool validiate(int x, int y) { return x > 0 && x <= N + 1 && y > 0 && y <= M + 1; }
int main()
{
    scanf("%d", &T);
    while (T--)
    {
        memset(dist, 0x3f, sizeof(dist));
        scanf("%d%d", &N, &M);
        for (int i = 1; i <= N; i++)
            scanf("%s", map[i] + 1);
        deque<ppr> qpool;
        qpool.push_back(make_pair(0, make_pair(1, 1)));
        while (!qpool.empty())
        {
            ppr curt = qpool.front();
            int x = curt.second.first, y = curt.second.second, k = curt.first;
            qpool.pop_front();
            if (dist[x][y] != INF)
                continue;
            dist[x][y] = k;
            for (int i = 0; i < 4; i++)
            {
                int a = x + dx[i], b = y + dy[i];
                if (validiate(a, b) && dist[a][b] == INF)
                {
                    if (sym[i] == map[min(a, x)][min(b, y)])
                        qpool.push_front(make_pair(k, make_pair(a, b)));
                    else
                        qpool.push_back(make_pair(k + 1, make_pair(a, b)));
                }
            }
        }
        if (dist[N][M] == INF)
            printf("NO SOLUTION\n");
        else
            printf("%d\n", dist[N + 1][M + 1]);
    }
    return 0;
}
```
