经典迷宫问题
难点在于判断:
判断移动是否合法并且没有来过
if(x < 1 || x > n || y < 1 || y > n || ~d[x][y])continue;
判断是否与上一个相同
if(g[x][y] == g[t.first][t.second])continue;
知识点:~(-1) == 0 ~0 = -1
#include
using namespace std;
typedef long long LL;
typedef pair<int, int> PII;
const int INF = 1e9,N = 110;
int n,d[N][N];
char g[N][N];
queue<PII> q;
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
int bfs(int ax,int ay) {
memset(d, -1, sizeof d);
d[ax][ay] = 0;
q.push({ax, ay});
while (!q.empty()) {
auto t = q.front();
q.pop();
for (int i = 0; i < 4; i ++ ) {
int x = dx[i] + t.first, y = dy[i] + t.second;
//判断移动是否合法
if(x < 1 || x > n || y < 1 || y > n || ~d[x][y])continue; //~(-1) == 0 ~0 = -1
//判断是否与上一个相同
if(g[x][y] == g[t.first][t.second])continue;
d[x][y] = d[t.first][t.second] + 1;
if(g[x][y] =='B') return d[x][y];
q.push({x, y});
}
}
return -1;
}
int main () {
ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
cin >> n;
int x, y;
for (int i = 1; i <= n; i ++) {
for (int j = 1; j <= n; j ++) {
cin >> g[i][j];
if(g[i][j] == 'A') {
x = i, y = j;
}
}
}
cout << bfs(x,y) << endl;
return 0;
}