奥赛一本通 1448 电路维修

1448 电路维修

题目大意

有一种正方形的电路元件,在它的两组相对顶点中,有一组会用导线连接起来,另一组则不会。将这些元件排成 $n$ 行 $m$ 列的电路板,至少要旋转多少个元件才能使左上角和右下角连通。

知识要点

广度优先搜索

解题思路

在所有的顶点中进行广搜,每次有四个方向,根据相应的导线方向确定这一次的代价是 1 或 0,代价为 1 加入队尾,代价为 0 则加入队头,这样可以保证搜索队列中的距离单调递增。

参考代码

#include <bits/stdc++.h>
using namespace std;

const int N = 505;
int t, m, n, d[N][N];
char g[N][N], s[] = "/\\/\\"; //需要旋转的对角线方向
int dx[] = {-1, -1, 1, 1}, dy[] = {-1, 1, 1, -1}; //移动方向
int ix[] = {-1, -1, 0, 0}, iy[] = {-1, 0, 0, -1}; //观察正方形的方向
struct Node {int x, y;};

int BFS() {
    deque<Node> Q;
    memset(d, 0x3f, sizeof(d));
    d[0][0] = 0, Q.push_back({0, 0});

    while(Q.size()) {
        int x = Q.front().x, y = Q.front().y;
        Q.pop_front();
        if(x == m && y == n) return d[x][y];

        for(int i = 0; i < 4; i++) {
            int nx = x + dx[i], ny = y + dy[i];
            if(nx < 0 || nx > m || ny < 0 || ny > n) continue;
            
            bool w = (g[x + ix[i]][y + iy[i]] == s[i]);
            if(d[nx][ny] <= d[x][y] + w) continue;
            d[nx][ny] = d[x][y] + w;
            if(w) Q.push_back({nx, ny});
            else Q.push_front({nx, ny});
        }
    }
    return -1;
}
int main() {
    scanf("%d", &t);
    while(t--) {
        scanf("%d%d", &m, &n);
        for(int i = 0; i < m; i++) scanf("%s", g[i]);
        if((m + n) & 1) puts("NO SOLUTION");
        else printf("%d\n", BFS());
    }
    return 0;
}
posted @ 2026-09-15 09:39  萧西待水  阅读(27)  评论(0)    收藏  举报