思路:
1.把输入样例存入预先设好的二维数组,也就是存图
2.
输入样例:
3
3 4
.S..
###.
..E.
3 4
.S..
.E..
....
3 4
.S..
####
..E.
输出样例:
5
1
oop!
AC:
#include <cstdio>
#include <cstring>
#include <iostream>
#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 dist[N][N];
//传说中的BFS没脑子模板
int bfs(PII start, PII end)
{
queue<PII> q;
memset(dist, -1, sizeof dist); // 把距离数组都初始化成-1
dist[start.x][start.y] = 0;
q.push(start);
int dx[4] = {-1, 0, 1, 0}; // ↑(-1, 0) ↓(1, 0)
int dy[4] = {0, 1, 0, -1}; // →(0, 1) ←(0, -1)
while (q.size())
{
auto t = q.front();
q.pop();
for (int i = 0; i < 4; i ++)
{
int x = t.x + dx[i];
int y = t.y + dy[i];
if (x < 0 || x >= n || y < 0 || y >= m) //越界
continue;
if (g[x][y] == '#') // 障碍物
continue;
if (dist[x][y] != -1) //之前已经遍历过
continue;
dist[x][y] = dist[t.x][t.y] + 1;
if (end == make_pair(x, y))
return dist[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 distance = bfs(start, end);
if (distance == -1)
puts("oop!");
else
printf("%d\n", distance);
}
return 0;
}