_S -> E #不可通过 求最短距离 无输出-1 _
输入样例:
3
3 4
.S..
###.
..E.
3 4
.S..
.E..
....
3 4
.S..
####
..E.
bfs 队列(queue)
C++ 代码
#include <bits/stdc++.h>
using namespace std;
const int N = 2e2+10;
int n,m,xi[] = {1,0,-1,0},yi[] = {0,1,0,-1};
int a[N][N],b[N][N];
int ans = 1e3,ret = 0;
struct str {
int x,y;
};
int bfs (str fist){
memset(b,-1,sizeof(b));
queue<str> q;
q.push(fist);
b[fist.x][fist.y] = 0;
while(q.size()){
auto t = q.front();
q.pop();
for(int i = 0; i < 4 ; i++){
int x = t.x + xi[i],y = t.y + yi[i];
if(x >= 1 && y >= 1 && x <= n && y <= m && a[x][y] && b[x][y] == -1){
b[x][y] = b[t.x][t.y] + 1;
q.push({x,y});
if(a[x][y] == 2 ) return b[x][y];
}
}
}
return -1;
}
int main(){
int t;
cin >> t;
while(t--){
memset (a, 0 ,sizeof(a));
cin >>n >> m;
ans = 1000;ret = 0;
int r,c;char ch;
str fist;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
cin >> ch;
if(ch == 'E') a[i][j] = 2;
else if(ch == 'S') fist.x = i,fist.y = j;
else if(ch == '.') a[i][j] = 1;
}
}
ans = bfs(fist);
if( ans == -1) cout <<"oop!"<<endl;
else cout<< ans <<endl;
}
return 0;
}