献给阿尔吉侬的花束
阿尔吉侬是一只聪明又慵懒的小白鼠,它最擅长的就是走各种各样的迷宫。
今天它要挑战一个非常大的迷宫,研究员们为了鼓励阿尔吉侬尽快到达终点,就在终点放了一块阿尔吉侬最喜欢的奶酪。
现在研究员们想知道,如果阿尔吉侬足够聪明,它最少需要多少时间就能吃到奶酪。
迷宫用一个 R×C 的字符矩阵来表示。
字符 S 表示阿尔吉侬所在的位置,字符 E 表示奶酪所在的位置,字符 # 表示墙壁,字符 . 表示可以通行。
阿尔吉侬在 1 个单位时间内可以从当前的位置走到它上下左右四个方向上的任意一个位置,但不能走出地图边界。
输入格式
第一行是一个正整数 T,表示一共有 T 组数据。
每一组数据的第一行包含了两个用空格分开的正整数 R 和 C,表示地图是一个 R×C 的矩阵。
接下来的 R 行描述了地图的具体内容,每一行包含了 C 个字符。字符含义如题目描述中所述。保证有且仅有一个 S 和 E。
输出格式
对于每一组数据,输出阿尔吉侬吃到奶酪的最少单位时间。
若阿尔吉侬无法吃到奶酪,则输出“oop!”(只输出引号里面的内容,不输出引号)。
每组数据的输出结果占一行。
数据范围
1<T≤10,
2≤R,C≤200
输入样例:
3
3 4
.S..
###.
..E.
3 4
.S..
.E..
....
3 4
.S..
####
..E.
输出样例:
5
1
oop!
理解dfs,bfs可以参考 这篇文章
#include <iostream>
#include <cstring>
#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]; //状态数组,判断矩阵中的点是否走过,同时记录该点到起点的最短距离。(没走过距离为-1,走过距离必为最小距离)
int bfs(PII start)
{
queue<PII> q;
q.push(start); //将起点入队
memset(dist, -1, sizeof dist); //将状态数组清零(所有点的状态都为没走过)
dist[start.x][start.y] = 0; //从起点出发,起点距离为0
int dx[] = { -1, 0, 1, 0 }, dy[] = { 0, 1, 0, -1 }; //小技巧,用偏移量来表示向 上,下,左,右,移动。
while (q.size())
{
auto t = q.front(); //取出队头元素,auto为自动识别并设为初始值的数据类型。
q.pop(); //提取后出队
for (int i = 0; i < 4; i++) //利用偏移量上下左右移动
{
int x = t.x + dx[i], y = t.y + dy[i]; //x,y为下一步要到的点的坐标
if (x >= 0 && x < n && y >= 0 && y < m && g[x][y] != '#' && dist[x][y] == -1) //符合条件(在矩阵内,不是障碍物,没有访问过的点)
{
dist[x][y] = dist[t.x][t.y] + 1;
if (g[x][y] == 'E') //找到终点则结束
return dist[x][y];
q.push({ x, y }); //不是终点就将该点入队
}
}
}
return -1;
}
int main()
{
int T;
cin >> T;
while (T--)
{
cin >> n >> m;
PII start;
for (int i = 0; i < n; i++)
{
cin >> g[i];
for (int j = 0; j < m; j++)
if (g[i][j] == 'S') start = { i, j }; //记录起点坐标
}
int res = bfs(start);
if (res == -1) puts("oop!");
else cout << res << endl;
}
return 0;
}
python
def bfs(x, y):
q = [(x, y)]
dist[x][y] = 0 #距离数组:与起点的距离
move = [(-1, 0), (0, 1), (1, 0), (0, -1)]
while len(q):
sx, sy = q.pop(0)
for i, j in move:
nx, ny = sx + i, sy + j
if 0 <= nx < r and 0 <= ny < c and g[nx][ny] != '#' and dist[nx][ny]==-1:
dist[nx][ny] = dist[sx][sy] + 1
if g[nx][ny] == 'E':
return dist[nx][ny]
q.append((nx, ny))
return 0
t = int(input())
while t:
t -= 1
g = []
x, y = 0, 0
r, c = map(int, input().split())
dist = [[-1] * c for _ in range(r)]
for i in range(r):
g.append(list(input()))
for j in range(c):
if g[i][j] == 'S':
x, y = i, j
res = bfs(x,y)
if res: print(res)
else: print('oop!')