hdu1180-bfs

xiaoxiao2021-02-28  82

题目中需要注意的是 1、地图中不会出现两个相连的梯子 2、从一个‘.’到下一个‘.’需要一分钟。而从这个‘.’经过楼梯到楼梯那边的‘.’也是一分钟。 3、如果楼梯暂时过不去,可以停留,等他转到能过再过。

根据题意,我们可以将下一步的情况分为以下几种 1、障碍或边界,或者已经走过了,直接返回。 2、‘.’或者‘T’直接走 3、楼梯 ①判断是否能过 ②如果不能就停一分钟

因为用的是bfs所以第一个搜到的就是最短时间,我看网上别人用的都是优先队列,可我用的队列也过了,不知道为什么=。= 大雾。(5.19更新,会用优先队列了,以后还是用优先队列吧)

#include <iostream> #include <cstring> #include <cstdio> #include <queue> using namespace std; char a[25][25]; int vis[25][25],m,n; int tx[] = {0,1,0,-1};//右下左上 int ty[] = {1,0,-1,0}; struct node { int x,y,time; }; bool judge(int x, int y) { if(x<0 || x>=n || y<0 || y>=m) return false; if(a[x][y]=='*' || vis[x][y]==1) return false; return true; } bool pass(int tox,int toy,node temp,int i) { if(a[tox][toy]=='-' && temp.time%2==0 && (i==0||i==2)) return true; else if(a[tox][toy]=='|' && temp.time%2==1 && (i==0||i==2)) return true; else if(a[tox][toy]=='-' && temp.time%2==1 && (i==1||i==3)) return true; else if(a[tox][toy]=='|' && temp.time%2==0 && (i==1||i==3)) return true; return false; } int bfs(int sx,int sy) { queue<node> q; node one; one.x = sx; one.y = sy; one.time = 0; q.push(one); vis[sx][sy] = 1; while(!q.empty()) { node temp = q.front(); q.pop(); if(a[temp.x][temp.y] =='T') return temp.time; for(int i=0; i<4; i++) { int tox = temp.x+tx[i]; int toy = temp.y+ty[i]; if(judge(tox,toy)) //首先判断下一步能不能走 { if(a[tox][toy]=='.' || a[tox][toy]=='T') //这种情况下直接走 { node next; next.x = tox; next.y = toy; next.time = temp.time+1; vis[tox][toy]=1; q.push(next); } else { if(pass(tox,toy,temp,i)) { tox = tox+tx[i]; toy = toy+ty[i]; if(judge(tox,toy)) { node next; next.x = tox; next.y = toy; next.time = temp.time+1; vis[tox][toy]=1; q.push(next); } } else //原地等一分钟再过楼梯 { node next; next.x = temp.x; next.y = temp.y; next.time = temp.time+1; q.push(next); } } } } } return -1; } int main() { int sx,sy; while(scanf("%d%d",&n,&m) != EOF) { for(int i=0; i<n; i++) { for(int j=0; j<m; j++) { cin >> a[i][j]; if(a[i][j] =='S') { sx = i; sy = j; } } } memset(vis,0,sizeof(vis)); int ans = bfs(sx,sy); printf("%d\n",ans); } return 0; }

写完这道题可以写下hdu1242练练手,bfs模板题。

转载请注明原文地址: https://www.6miu.com/read-77249.html

最新回复(0)