AcWing 3179. 穿越雷区--经典bfs问题
原题链接
简单
作者:
ycqs
,
2021-04-15 16:14:12
,
所有人可见
,
阅读 439
C++ 代码
#include<iostream>
#include<queue>
using namespace std;
char m[100][100]; //地图
int vis[100][100]; //标记
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1}; //方向
int n;
struct node{ //结点信息
int x;
int y;
int step;
char ch;
} first;
int bfs(node fs){
queue<node> q;
q.push(fs);
while(!q.empty()){
node now = q.front();
if(now.ch == 'B')return now.step;
q.pop();
for (int i = 0; i < 4; i ++ ){
int nx = now.x + dx[i];
int ny = now.y + dy[i];
if(nx>=1 && nx<=n && ny>=1 && ny<=n && m[nx][ny]!=m[now.x][now.y] && !vis[nx][ny]){
node next;
next.x = nx;
next.y = ny;
next.step = now.step + 1;
next.ch = m[nx][ny];
vis[nx][ny] = 1;
q.push(next);
}
}
}
return -1;
}
int main(){
cin>>n;
for(int i=1; i<=n; i++){
for(int j=1; j<=n; j++){
cin>>m[i][j];
if(m[i][j] == 'A'){
first.x = i;
first.y = j;
first.ch = 'A';
first.step = 0;
}
}
}
cout<<bfs(first);
return 0;
}