求最少单位时间,用bfs较佳
bfs找到一条合法路径
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <queue>
#define x first
#define y second
using namespace std;
typedef pair<int, int> PII;
const int N = 210;
int n,m;
char g[N][N];
int d[N][N];
int dx[4] = {-1,0,1,0},dy[4] = {0,1,0,-1};
int bfs(PII start,PII end){
queue<PII> q;
memset(d,-1,sizeof d);
d[start.x][start.y] = 0;
q.push(start);
while(q.size()){
auto t = q.front();
q.pop();
for(int i = 0;i < 4;++i){
int x = t.x + dx[i],y = t.y + dy[i];
if(x < 0 || x >= n || y < 0 || y >= m) continue;
if(g[x][y] == '#') continue;
if(d[x][y] != -1) continue;
d[x][y] = d[t.x][t.y] + 1;
if(end == make_pair(x,y)) return d[x][y];
q.push({x,y});
}
}
return -1;
}
int main(){
int T;
scanf("%d",&T);
while(T--){
scanf("%d%d",&n,&m);
for(int i = 0;i < n;++i) scanf("%s",g[i]);
PII start,end;
for(int i = 0;i < n;++i){
for(int j = 0;j < m;++j){
if(g[i][j] == 'S') start = {i,j};
else if(g[i][j] == 'E') end = {i,j};
}
}
int dist = bfs(start,end);
if(dist == -1) printf("oop!\n");
else printf("%d\n",dist);
}
return 0;
}