个人认为这个代码写的比较清晰, 希望能帮助到大家^^
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
typedef pair<int, int > PII;
const int NUMBER = 510, INF = 0x3f3f3f3f;
const int dx1[4] = {-1, -1, 1, 1}, dy1[4] = {-1, 1, 1, -1};
const int dx2[4] = {-1, -1, 0, 0}, dy2[4] = {-1, 0, 0, -1};
const char map[5] = {'\\', '/', '\\', '/'};
int row, col;
char graph[NUMBER][NUMBER];
int dist[NUMBER][NUMBER];
bool visited[NUMBER][NUMBER];
//双端队列本质是dijkstra算法, 因此需要前置数组初始化
void bfs() {
memset(dist, 0x3f, sizeof dist);
memset(visited, false, sizeof visited);
dist[0][0] = 0;
PII queue[NUMBER * NUMBER * 2];
int head = NUMBER * NUMBER, tail = head - 1;
queue[++tail] = {0, 0};
while (head <= tail) {
PII _node = queue[head++];
if (visited[_node.first][_node.second]) continue;
visited[_node.first][_node.second] = true;
for (int i = 0; i < 4; ++i) {
int new_x = _node.first + dx1[i];
int new_y = _node.second + dy1[i];
if (new_x < 0 || new_x > row || new_y < 0 || new_y > col) continue;
// 获取到当前电线块的位置
int x_pos = _node.first + dx2[i];
int y_pos = _node.second + dy2[i];
// 计算当前位置的电线需不需要翻转
int val = graph[x_pos][y_pos] == map[i] ? 0 : 1;
int new_dist = dist[_node.first][_node.second] + val;
if (new_dist < dist[new_x][new_y]) {
dist[new_x][new_y] = new_dist;
if (val) {
queue[++tail] = {new_x, new_y};
}
else {
queue[--head] = {new_x, new_y};
}
}
}
}
}
int main() {
int cases;
scanf("%d", &cases);
while (cases--) {
scanf("%d%d", &row, &col);
for (int i = 0; i < row; ++i) scanf("%s", graph[i]);
bfs();
int res = dist[row][col];
if (res == INF) puts("NO SOLUTION");
else printf("%d\n", res);
}
return 0;
}