AcWing 844. 走迷宫
原题链接
简单
作者:
Value
,
2020-05-11 21:06:19
,
所有人可见
,
阅读 519
#include <iostream>
#include <queue>
using namespace std;
const int N = 110;
int graphs[N][N];
bool vis[N][N];
int n, m;
void read(){
cin >> n >> m;
for(int i = 0; i < n; i ++ ){
for(int j = 0; j < m; j ++ ){
cin >> graphs[i][j];
}
}
}
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, 1, 0, -1};
typedef pair<int ,int> pii;
struct node{
pii loc;
int step;
};
int bfs(){
vis[0][0] = true;
queue<node> qu;
qu.push({{0, 0}, 0});
while(!qu.empty()){
node now = qu.front();
qu.pop();
for(int i = 0; i < 4; i ++ ){
int xx = now.loc.first + dx[i];
int yy = now.loc.second + dy[i];
if(xx == n - 1 && yy == m - 1) return now.step+1;
if(xx >= 0 && xx < n && yy >= 0 && yy < m && !vis[xx][yy] && !graphs[xx][yy]){
vis[xx][yy] = true;
qu.push({{xx, yy}, now.step + 1});
}
}
}
return -1;
}
int main(){
read();
cout << bfs() << endl;
return 0;
}