https://www.acwing.com/problem/content/description/1103/
阿尔吉侬是一只聪明又慵懒的小白鼠,它最擅长的就是走各种各样的迷宫。
今天它要挑战一个非常大的迷宫,研究员们为了鼓励阿尔吉侬尽快到达终点,就在终点放了一块阿尔吉侬最喜欢的奶酪。
现在研究员们想知道,如果阿尔吉侬足够聪明,它最少需要多少时间就能吃到奶酪。
迷宫用一个 R×C 的字符矩阵来表示。
字符 S 表示阿尔吉侬所在的位置,字符 E 表示奶酪所在的位置,字符 # 表示墙壁,字符 . 表示可以通行。
阿尔吉侬在 1 个单位时间内可以从当前的位置走到它上下左右四个方向上的任意一个位置,但不能走出地图边界。
输入格式
第一行是一个正整数 T,表示一共有 T 组数据。
每一组数据的第一行包含了两个用空格分开的正整数 R 和 C,表示地图是一个 R×C 的矩阵。
接下来的 R 行描述了地图的具体内容,每一行包含了 C 个字符。字符含义如题目描述中所述。保证有且仅有一个 S 和 E。
输出格式
对于每一组数据,输出阿尔吉侬吃到奶酪的最少单位时间。
若阿尔吉侬无法吃到奶酪,则输出“oop!”(只输出引号里面的内容,不输出引号)。
每组数据的输出结果占一行。
解题思路:用bfs搜索
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<string>
#include<iostream>
#include<cstring>
#include<vector>
using namespace std;
#define ll long long
struct node
{
int x,y,s;
};
struct node que[40005];
int nextt[4][2] = {{0,1},{1,0},{0,-1},{-1,0}};
char s[205][205];
int book[205][205];
int main(){
int t;
scanf("%d",&t);
while(t--){
memset(book,0,sizeof(book));
int r,c;
scanf("%d%d",&r,&c);
int head,tail,tx,ty;
int startx,starty;
for(int i=0; i<r; ++i){
for(int j=0; j<c; ++j){
scanf(" %c",&s[i][j]);
if(s[i][j]=='S'){
startx = i;
starty = j;
}
}
}
// for(int i=0; i<r; ++i){
// for(int j=0; j<c; ++j){
// printf("%c",s[i][j]);
// }
// printf("\n");
// }
head = tail = 1;
que[tail].x = startx;
que[tail].y = starty;
que[tail].s = 0;
tail++;
int flag = 0;
while(head<tail){
for(int k=0; k<4; ++k){
tx = que[head].x + nextt[k][0]; //这里是head
ty = que[head].y + nextt[k][1];
if(tx<0||tx>=r||ty<0||ty>=c){
continue;
}
if((s[tx][ty]=='.'||s[tx][ty]=='E')&&book[tx][ty]==0){
book[tx][ty] = 1;
que[tail].x = tx; //这里是tail
que[tail].y = ty;
que[tail].s = que[head].s+1;
tail++;
}
if(s[tx][ty]=='E'){
flag = 1;
break;
}
}
if(flag==1) break;
head++;
}
if(flag == 1){
printf("%d\n",que[tail-1].s);
}
else
printf("oop!\n");
}
return 0;
}