1101. 獻給阿爾吉侬的花束
阿爾吉侬是一隻聰明又慵懶的小白鼠,它最擅長的就是走各種各樣的迷宮。
今天它要挑戰一個非常大的迷宮,研究員們為了鼓勵阿爾吉侬盡快到達終點,就在終點放了一塊阿爾吉侬最喜歡的奶酪。
現在研究員們想知道,如果阿爾吉侬足夠聰明,它最少需要多少時間就能吃到奶酪。
迷宮用一個 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!
思路:
寬搜,注意一下以前的寫法,都是在隊列中取出的時候進行标記,這裡會逾時
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
typedef pair<int, int> P;
int r,c;
char mp[205][205];
int dist[205][205];
int sx, sy;
bool check(int x, int y){
return x < 0 || x >= r || y < 0 || y >= c || mp[x][y] == '#';
}
int bfs(){
memset(dist, 0, sizeof dist);
queue<P> que;
que.push(P(sx, sy));
dist[sx][sy] = 0;
while(que.size()){
P top = que.front();
que.pop();
int dx[4] = {0 , 0, 1, -1}, dy[4] = {1, -1, 0, 0};
for(int i = 0; i < 4; i++){
int tx = top.first + dx[i], ty = top.second + dy[i];
if(check(tx, ty))continue;
if(mp[tx][ty] == 'E'){
return dist[top.first][top.second]+1;
}
que.push(P(tx, ty));
dist[tx][ty] = dist[top.first][top.second] + 1;
mp[tx][ty] = '#'; // 如果把标記走過的點放在從隊列中取出的時候進行标記,會逾時
}
}
return -1;
}
int main(){
int t;
cin>>t;
while(t--){
scanf("%d%d", &r, &c);
for(int i = 0; i < r; i++){
scanf("%s", mp[i]);
}
for(int i = 0; i < r; i++)
for(int j = 0; j < c; j++){
if(mp[i][j] == 'S'){
sx = i, sy = j;
}
}
mp[sx][sy] = '#';
int ans = bfs();
if(ans == -1){
cout<<"oop!"<<endl;
}else{
cout<<ans<<endl;
}
}
}