POJ 3170--双重BFS
来源:互联网 发布:网络发票查询 编辑:程序博客网 时间:2024/05/18 02:40
题意:
给一个 n 列 m行的矩阵,矩阵元素只有0,1,2,3,4,0表示可通过,1表示不可通过,矩阵中只有一个2和3,其他数字不限制,的问从2
开始到所有的4在折回到3的最短路是多少。
输入:
8 44 1 0 0 0 0 1 00 0 0 1 0 1 0 00 2 1 1 3 0 4 00 0 0 4 1 1 1 0输出:
11分析:
两个BFS,先从2到4,再从4到3.
代码:
#include <iostream>#include <queue>#include <cstdio>#include <cstring>#include <algorithm>#define inf 0x3f3f3f3fusing namespace std;const int maxn=1005;int a[maxn][maxn],vis[maxn][maxn],dist1[maxn][maxn],dist2[maxn][maxn];int n,m,ans;int dr[]= {0,0,1,-1};int dc[]= {1,-1,0,0};struct node{ int x,y;} s1,s2,t;void bfs(){ queue<node> q; dist1[s1.x][s1.y]=0; q.push(s1); while(!q.empty()) { node p=q.front(); q.pop(); int r=p.x; int c=p.y; for(int i=0; i<4; i++) { int rr=r+dr[i]; int cc=c+dc[i]; if(rr>=1&&rr<=m&&cc>=1&&cc<=n&&a[rr][cc]!=1&&dist1[rr][cc]==inf) { vis[rr][cc]=1; t.x=rr; t.y=cc; dist1[rr][cc]=dist1[r][c]+1; q.push(t); } } } while(!q.empty()) q.pop(); dist2[s2.x][s2.y]=0; q.push(s2); while(!q.empty()) { node p=q.front(); q.pop(); int r=p.x; int c=p.y; for(int i=0; i<4; i++) { int rr=r+dr[i]; int cc=c+dc[i]; if(rr>=1&&rr<=m&&cc>=1&&cc<=n&&a[rr][cc]!=1&&dist2[rr][cc]==inf) { vis[rr][cc]=1; t.x=rr; t.y=cc; dist2[rr][cc]=dist2[r][c]+1; q.push(t); } } } for(int i=1; i<=m; i++) { for(int j=1; j<=n; j++) { if(a[i][j]==4&&dist1[i][j]!=inf&&dist2[i][j]!=inf) ans=min(ans,dist1[i][j]+dist2[i][j]); } }}int main(){ scanf("%d%d",&n,&m); for(int i=1; i<=m; i++) { for(int j=1; j<=n; j++) { scanf("%d",&a[i][j]); if(a[i][j]==2) { s1.x=i; s1.y=j; } if(a[i][j]==3) { s2.x=i; s2.y=j; } } } memset(dist2,inf,sizeof(dist2)); memset(dist1,inf,sizeof(dist1)); ans=inf; bfs(); printf("%d\n",ans); return 0;}
0 0
- POJ 3170--双重BFS
- POJ 1475 Pushing Boxes (双重BFS/推箱子游戏)
- 双重 BFS —— POJ 1475 Pushing Boxes
- 推箱子(双重bfs)
- POJ 3170 BFS 水题
- pku 1475 Pushing Box 双重BFS
- uva 589 - Pushing Boxes(双重bfs)
- HDU 2612 Find a way【双重BFS】
- FZU 2150 Fire Game (双重BFS)
- HDU 1254 推箱子(双重BFS)
- Find a way (双重BFS)
- HDU-3713:Double Maze(双重BFS)
- HDU 1254 推箱子(双重bfs)
- POJ 2387 Bellman双重边
- Poj 1836 Alignment (双重LIS)
- [BFS] poj
- poj 3170 Knights of Ni (bfs)
- POJ 3170(bfs求最短路)
- hdu 1181 变形课(DFS)
- The Frog's Games(二分)
- 用windows自带功能轻松建立自己的FTP网站
- Trie树[前缀树,字典树]
- Oracle 11g R2 DBA 操作指南(7)
- POJ 3170--双重BFS
- 大数据hadoop资源网址
- Android签名机制之---签名过程详解
- 【整理】div与span的区别
- MultiPath TCP - Users - Manual
- 栈
- 生活、工作点滴(一)
- Android:基于百度云推送的聊天系统
- jQuery 网络请求及 JSON 数据处理