【HRBUST - 1621】迷宫问题II (bfs)
題干:
小z身處在一個(gè)迷宮中,小z每分鐘可以走到上下左右四個(gè)方向的相鄰格之一。迷宮中有一些墻和障礙物。
同時(shí)迷宮中也有一些怪獸,當(dāng)小z碰到任意一個(gè)怪獸時(shí),小z需要將怪獸消滅掉才可以離開此方格。但消滅
怪獸會(huì)花費(fèi)一定的時(shí)間。現(xiàn)在小z想知道走出迷宮需要花費(fèi)的最少時(shí)間。
Input
輸入第一行為組數(shù)T(T<=10)。
對(duì)于每組數(shù)據(jù)第一行為兩個(gè)整數(shù)R和C(1<=R,C<=200)。以下R行每行有C個(gè)字符,即迷宮地圖。
其中"#"代表墻和障礙物,"."表示空地,[1~9]的數(shù)字代表此處有怪獸以及消滅此處的怪獸需要的時(shí)間.
"Z"表示小z的起始位置,"W"表示迷宮出口。
對(duì)于每組數(shù)據(jù)保證起始位置和迷宮出口唯一。
Output
對(duì)于每組數(shù)據(jù),輸出走出迷宮的最短時(shí)間(單位:分鐘)。如果無法走出迷宮則輸出"IMPOSSIBLE"。
Sample Input
2
3 4
.Z..
.234
#.W.
4 4
Z.1.
.32.
##4.
W#..
Sample Output
5
IMPOSSIBLE
Hint
解題報(bào)告:
? ? ?優(yōu)先隊(duì)列搞一波pq,如果是普通的bfs,那么隊(duì)列即可,因?yàn)殛?duì)列就能保證取出來的Node結(jié)構(gòu)體的t是最小值,但是這題不一樣,所以需要pq。剛開始寫的時(shí)候wa了好幾發(fā)最后發(fā)現(xiàn)是main函數(shù)中那個(gè)雙層循環(huán)的內(nèi)層循環(huán)寫成了for(int j=i; j<=m; j++)、、、我也是醉了好像不止第一次錯(cuò)在這里了、、、
AC代碼:
#include<cstdio> #include<queue> #include<cstring> #include<cmath> #include<map> #include<iostream> #include<algorithm> #define ll long long using namespace std; struct Node {int x,y;int t;Node(){}Node(int x,int y,int t):x(x),y(y),t(t){} bool operator<(const Node b) const{return t > b.t;} }; int n,m; int nx[4]={0,1,0,-1}; int ny[4]={1,0,-1,0}; bool vis[205][205]; char maze[205][205]; int bfs(int sx,int sy) {priority_queue<Node> pq;pq.push(Node(sx,sy,0));Node cur;int tx,ty;while(pq.size()) {cur=pq.top();pq.pop(); for(int k = 0; k<4; k++) {tx = cur.x + nx[k];ty = cur.y + ny[k];if(maze[tx][ty] == '#' || vis[tx][ty] || tx < 1 || tx > n || ty < 1 || ty > m) continue;vis[tx][ty]=1;if(maze[tx][ty] == 'W') return cur.t + 1;else if(maze[tx][ty] == '.') pq.push(Node(tx,ty,cur.t+1));else pq.push(Node(tx,ty,cur.t + 1 + maze[tx][ty] - '0'));}}return -1;} int main() {int t,sx,sy;cin>>t;while(t--) {scanf("%d%d",&n,&m);memset(vis,0,sizeof vis);for(int i = 1; i<=n; i++) {scanf("%s",maze[i]+1);}for(int i = 1; i<=n; i++) {for(int j = 1; j<=m; j++) {if(maze[i][j] == 'Z') {sx=i,sy=j;break;}}}int ans = bfs(sx,sy);if(ans == -1) puts("IMPOSSIBLE");else printf("%d\n",ans);}return 0 ; }?
總結(jié)
以上是生活随笔為你收集整理的【HRBUST - 1621】迷宫问题II (bfs)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: NASA公布一神秘火箭曾撞击月球 形成2
- 下一篇: 【Gym - 101986F】Pizza