题目来源 www.acwing.com/problem/content/1103/
题目 阿尔吉侬是一只聪明又慵懒的小白鼠,它最擅长的就是走各种各样的迷宫。
今天它要挑战一个非常大的迷宫,研究员们为了鼓励阿尔吉侬尽快到达终点,就在终点放了一块阿尔吉侬最喜欢的奶酪。
现在研究员们想知道,如果阿尔吉侬足够聪明,它最少需要多少时间就能吃到奶酪。
迷宫用一个 R×C 的字符矩阵来表示。
字符 S 表示阿尔吉侬所在的位置,字符 E 表示奶酪所在的位置,字符 # 表示墙壁,字符 . 表示可以通行。
阿尔吉侬在 1 个单位时间内可以从当前的位置走到它上下左右四个方向上的任意一个位置,但不能走出地图边界。
输入格式 第一行是一个正整数 T,表示一共有 T 组数据。
每一组数据的第一行包含了两个用空格分开的正整数 R 和 C,表示地图是一个 R×C 的矩阵。
接下来的 R 行描述了地图的具体内容,每一行包含了 C 个字符。字符含义如题目描述中所述。保证有且仅有一个 S 和 E。
输出格式 对于每一组数据,输出阿尔吉侬吃到奶酪的最少单位时间。
若阿尔吉侬无法吃到奶酪,则输出“oop!”(只输出引号里面的内容,不输出引号)。
每组数据的输出结果占一行。
数据范围 1<T≤10,
2≤R,C≤200
输入样例: 1 2 3 4 5 6 7 8 9 10 11 12 13 3 3 4 .S.. ###. ..E. 3 4 .S.. .E.. .... 3 4 .S.. #### ..E.
输出样例:
AC代码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 #include <iostream> #include <queue> #include <cstring> using namespace std ; #define x first #define y second typedef pair <int ,int > PII;const int MAX = 202 ;char map [MAX][MAX]; int dis[MAX][MAX]; int max_x,max_y; int moving[4 ][2 ] = {{0 ,1 },{0 ,-1 },{1 ,0 },{-1 ,0 }}; bool isTrue (PII loc) { return loc.x >= 0 && loc.x < max_x && loc.y >= 0 && loc.y <max_y && map [loc.x][loc.y] != '#' ; } void bfs (PII start) { map [start.x][start.y] = '#' ; queue <PII> q; q.push(start); while (!q.empty()){ PII now = q.front(); PII next; q.pop(); for (int i = 0 ; i < 4 ; i++){ next.x = now.x + moving[i][0 ]; next.y = now.y + moving[i][1 ]; if (isTrue(next)){ if (map [next.x][next.y] == '.' ){ q.push(next); dis[next.x][next.y] = dis[now.x][now.y] + 1 ; map [next.x][next.y] = '#' ; } if (map [next.x][next.y] == 'E' ){ cout <<dis[now.x][now.y]+1 <<endl ; return ; } } } } cout <<"oop!" <<endl ; } int main () { int n; cin >>n; int i = 0 ; while (n--){ memset (map , '#' , sizeof (map )); memset (dis, 0 , sizeof (dis)); PII start; cin >>max_x>>max_y; for (int i = 0 ; i < max_x; i++) cin >>map [i]; for (int i = 0 ; i < max_x; i++){ for (int j = 0 ; j < max_y; j++){ if (map [i][j] == 'S' ){ start.x = i; start.y = j; } } } bfs(start); } return 0 ; }