AcWing 1099. 仙岛求药
原题链接
简单
作者:
Value
,
2020-06-27 21:18:08
,
所有人可见
,
阅读 491
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
const int N = 310;
char graph[N][N];
bool vis[N][N];
int n, m;
typedef pair<int, int> pii;
pii st, ed;
struct node{
pii loc;
int step;
};
int dic[4][2] = {
{0, -1}, {-1, 0}, {0, 1}, {1, 0}
};
bool check(int x, int y){
if(x >= 0 && x < n && y >= 0 && y < m) return true;
return false;
}
int bfs(){
queue<node> qu;
qu.push({st, 0});
vis[st.first][st.second] = true;
while(!qu.empty()){
node now = qu.front();
qu.pop();
for(int i = 0; i < 4; i ++ ){
int xx = now.loc.first + dic[i][0];
int yy = now.loc.second + dic[i][1];
if(xx == ed.first && yy == ed.second) return now.step + 1;
if(check(xx, yy) && !vis[xx][yy] && graph[xx][yy] != '#'){
vis[xx][yy] = true;
qu.push({{xx, yy}, now.step + 1});
}
}
}
return -1;
}
int main(){
while(cin >> n >> m && n && m){
memset(vis, false, sizeof vis);
for(int i = 0; i < n; i ++ ){
for(int j = 0; j < m; j ++ ){
cin >> graph[i][j];
if(graph[i][j] == '@') st = {i, j};
if(graph[i][j] == '*') ed = {i, j};
}
}
cout << bfs() << endl;
}
return 0;
}