uva1600-Patrol Robot(bfs)
来源:互联网 发布:商家平台源码 编辑:程序博客网 时间:2024/06/14 18:47
题意:
给出了机器人要行走的迷宫,还有机器人一次最多能穿过的墙的数目K,求最短的路径。
思路:一开始只是简单的用二维数组标记走过的路径,wa了,后来才看了别人的题解才知道,二维的标记有时会陷入死胡同。
#include<iostream>#include<cstring>using namespace std;int maze[22][22],vis[22][22][22];struct{int x,y,c,pre;}a[100000];int dx[4]={0,0,1,-1};int dy[4]={1,-1,0,0};int m,n,k;int co,flag;void pri(int p){if(a[p].pre!=-1){co++;pri(a[p].pre);}}void bfs(){memset(vis,0,sizeof(vis));int now=1,bu=0;a[0].x=0;a[0].y=0;a[0].pre=-1;a[0].c=0;while(bu<now){for(int i=0;i<4;i++){int sx=a[bu].x+dx[i];int sy=a[bu].y+dy[i];if(sx<0||sy<0||sy>=m||sx>=n) {continue;}if(maze[sy][sx]==1) a[now].c=a[bu].c+1;else a[now].c=0; if(vis[sy][sx][a[now].c]||a[bu].c>k) {continue;}else{vis[sy][sx][a[now].c]=1;a[now].x=sx;a[now].y=sy;a[now].pre=bu;now++;}if(sy==m-1&&sx==n-1){pri(bu); flag=1;return;}}bu++;} }int main(){int t;cin>>t; while(t--){co=1;flag=0;cin>>m>>n>>k;for(int i=0;i<m;i++)for(int j=0;j<n;j++)cin>>maze[i][j];bfs();if(m==1&&n==1) cout<<0<<endl;else if(flag) cout<<co<<endl;else cout<<-1<<endl; }}我是用数组进行标记,比较繁琐,有大神是通过队列标记的一边入队列一边弹出来,感觉更加简练,附上大神代码
#include<cstdio> #include<cstring> #include<iostream> #include<queue> using namespace std; int n,m,k,t; int map[25][25]; bool vis[25][25][25];//增加一个维度Z来表示跃过的墙的层数。 int dx[4]= {1,0,-1,0}; int dy[4]= {0,1,0,-1}; struct Point { int x,y; int step; int layer; Point(int x=1,int y=1,int step=0,int layer=0):x(x),y(y),step(step),layer(layer) {} }; int ans() { queue<Point>Q; memset(vis,0,sizeof(vis)); Point a(1,1,0,0); Point end_point(n,m); Q.push(a); vis[1][1][0]=true; while(!Q.empty()) { Point now=Q.front(); Q.pop(); if(now.x==end_point.x&&now.y==end_point.y) return now.step; for(int i=0; i<4; i++) { int x=dx[i]+now.x; int y=dy[i]+now.y; int layer=now.layer; if(map[x][y]) layer++;//因为每次只会移动一步。而且遇见一层墙,所以加加。 else layer=0; if(layer<=k&&!vis[x][y][layer]&&x>=1&&y>=1&&x<=n&&y<=m) { vis[x][y][layer]=true; Q.push(Point(x,y,now.step+1,layer)); } } } return -1; } int main() { cin>>t; while(t--) { cin>>n>>m>>k;//输入行和列以及k值! for(int i=1; i<=n; i++) for(int j=1; j<=m; j++) cin>>map[i][j];//输入地图 cout<<ans()<<endl; } return 0; }
阅读全文
0 0
- uva1600-Patrol Robot(bfs)
- Uva1600 - Patrol Robot(bfs解法)
- 习题6-5 UVa1600 Patrol Robot(BFS)
- uva1600 Patrol Robot 巡逻机器人(BFS)
- Uva1600 Patrol Robot 【bfs】【习题6-5】
- uva1600 Patrol Robot —— bfs
- uva1600 - Patrol Robot
- UVA1600 - Patrol Robot
- uva1600 Patrol Robot
- uva1600 -- Patrol Robot
- UVA1600 Patrol Robot
- Patrol Robot(BFS)
- Patrol Robot UVa1600巡逻机器人
- Uva1600——Patrol Robot
- Patrol Robot UVa1600巡逻机器人
- 1600 - Patrol Robot(BFS)
- Patrol Robot (BFS典例)
- UVA 1600 - Patrol Robot( BFS & DFS)
- opencv常见函数
- Java8 Lambda语法 示例
- serializer嵌套序列化
- Counting Divisors (2017 多校4)“素 数 筛”
- 数据结构之二叉树
- uva1600-Patrol Robot(bfs)
- LeetCode 474. Ones and Zeroes 动态规划解法+拓展
- Socket抽象类的工程应用
- 【LeetCode】189. Rotate Array
- Set up CodeBlocks for OpenCV
- gcd公式
- Java 、 Android 面试题
- 快速排序
- [PAT乙级]1054. 求平均值 (20)