HDU - 2612 Find a way (bfs)

mac2022-06-30  27

题意:给出两个人的位置,以及多个KFC位置, 障碍位置求能到达的最近KFC位置思路:两个位置搜索,然后记录到各KFC的时间信息,再选则最近的距离 最后得到的时总和的时间

 

完整代码:

#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <queue> using namespace std; const int inf = 0x3f3f3f3f; char g[205][205]; int vis[205][205],n,m,cnt; int mov[4][2]={{0,1},{1,0},{-1,0},{0,-1}}; struct node { int x; int y; int step; }; node path1[1001]; node path2[1001]; void bfs(node s,node path[]) { memset(vis,0,sizeof(vis)); queue<node>q; q.push(s); while(!q.empty()) { s=q.front(); q.pop(); if(g[s.x][s.y]=='@') path[cnt++]=s; for(int i=0;i<4;i++) { int nx=s.x+mov[i][0]; int ny=s.y+mov[i][1]; if(nx<0||ny<0||nx>=n||ny>=m||g[nx][ny]=='#') continue; //边界或障碍 if(vis[nx][ny]) continue; // 已访问 vis[nx][ny]=1; node nex; nex.x=nx,nex.y=ny,nex.step=s.step+1; q.push(nex); } } } int main() { while(scanf("%d%d",&n,&m)==2) { memset(path1,0,sizeof(path1)); memset(path2,0,sizeof(path2)); cnt=0; getchar(); int x1,y1,x2,y2; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { scanf("%c",&g[i][j]); if(g[i][j]=='Y') x1=i,y1=j; if(g[i][j]=='M') x2=i,y2=j; } getchar(); } node s,e; s.x=x1,s.y=y1,s.step=0; bfs(s,path1); int cnt1=cnt; cnt=0; s.x=x2,s.y=y2,s.step=0; bfs(s,path2); int cnt2=cnt; int Min=inf; for(int i=0;i<cnt1;i++) { for(int j=0;j<cnt2;j++) { if(path1[i].x==path2[j].x&&path1[i].y==path2[j].y) Min=min(Min,11*(path1[i].step+path2[j].step)); } } printf("%d\n",Min); } return 0; }  

 

转载于:https://www.cnblogs.com/Tianwell/p/11265542.html

相关资源:JAVA上百实例源码以及开源项目
最新回复(0)