AcWing 1101. 献给阿尔吉侬的花束
原题链接
简单
作者:
Value
,
2020-07-15 16:52:50
,
所有人可见
,
阅读 569
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
const int N = 210;
char graph[N][N];
bool vis[N][N];
int n, m;
typedef pair<int, int> pii;
struct node{
pii loc;
int step;
};
pii st, ed;
void read(){
cin >> n >> m;
for(int i = 0; i < n; i ++ ){
for(int j = 0; j < m; j ++ ){
cin >> graph[i][j];
if(graph[i][j] == 'S') st = {i, j};
else if(graph[i][j] == 'E') ed = {i, j};
}
}
}
bool check(int x, int y){
return x >= 0 && x < n && y >= 0 && y < m;
}
int bfs(){
int dic[4][2] = {
{-1, 0}, {0, 1}, {1, 0}, {0, -1}
};
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 x = now.loc.first + dic[i][0];
int y = now.loc.second + dic[i][1];
if(x == ed.first && y == ed.second) return now.step + 1;
if(check(x, y) && graph[x][y] != '#' && !vis[x][y]){
vis[x][y] = true;
qu.push({{x, y}, now.step + 1});
}
}
}
return -1;
}
int main(){
int T; cin >> T;
while(T -- ){
memset(vis, false, sizeof vis);
read();
int res = bfs();
if(res == -1) cout << "oop!" << endl;
else cout << res << endl;
}
return 0;
}