HDU 2822 Dogs【两次bfs】
2015-03-24 21:17
260 查看
6 6
..X...
XXX.X.
....X.
X.....
X.....
X.X...
3 5 6 3
如上一个图 告诉起点和终点 X到达不费力气 .到达花费1 问从起点到终点 最少的花费力气
分析:bfs 遇到X在bfs
代码:
View Code
..X...
XXX.X.
....X.
X.....
X.....
X.X...
3 5 6 3
如上一个图 告诉起点和终点 X到达不费力气 .到达花费1 问从起点到终点 最少的花费力气
分析:bfs 遇到X在bfs
代码:
#include <iostream> #include <cstdio> #include <cstring> #include <queue> using namespace std; const int maxn = 1005; char s[maxn][maxn]; int vis[maxn][maxn]; int n, m; int x0, y0, xn, yn; struct Node { int x, y, id; bool operator<(const Node &n0) const{ return id > n0.id; } }; priority_queue<Node> q, qq; int xx[4] = { 0, 0, 1, -1 }; int yy[4] = { 1, -1, 0, 0 }; bool bfs2(Node n0) { while(!qq.empty()) { qq.pop(); } qq.push(n0); Node n2; while(!qq.empty()) { Node n1 = qq.top(); qq.pop(); if(n1.x == xn && n1.y == yn) return true; for(int i = 0; i < 4; i++) { int tx = n1.x + xx[i]; int ty = n1.y + yy[i]; if(tx >= 0 && tx < n && ty >= 0 && ty < m && !vis[tx][ty] && s[tx][ty] == 'X') { vis[tx][ty] = vis[n1.x][n1.y]; n2.x = tx; n2.y = ty; n2.id = vis[tx][ty]; qq.push(n2); q.push(n2); } } } return false; } void bfs() { while(!q.empty()) q.pop(); memset(vis, 0, sizeof(vis)); vis[x0][y0] = 1; Node n0 = (Node) {x0, y0, vis[x0][y0]}; q.push(n0); if(s[x0][y0] == 'X') { if(bfs2(n0)) return; } Node n2; while(!q.empty()) { Node n1 = q.top();q.pop(); if(n1.x == xn && n1.y == yn) return ; for(int i = 0; i < 4; i++) { int tx = n1.x + xx[i]; int ty = n1.y + yy[i]; if(tx >= 0 && tx < n && ty >= 0 && ty < m && !vis[tx][ty]) { if(s[tx][ty] == 'X') { vis[tx][ty] = vis[n1.x][n1.y]; n2.x = tx; n2.y = ty; n2.id = vis[tx][ty]; if(bfs2(n2)) return ; q.push(n2); } else { vis[tx][ty] = vis[n1.x][n1.y] + 1; n2.x = tx; n2.y = ty; n2.id = vis[tx][ty]; q.push(n2); } } } } } int main() { while(scanf("%d %d",&n, &m) ) { if(n == 0 && m == 0) break; for(int i = 0; i < n; i++) { scanf("%s",s[i]); } scanf("%d %d %d %d",&x0, &y0, &xn, &yn); x0--; y0--; xn--; yn--; bfs(); printf("%d\n", vis[xn][yn] - 1); } return 0; }
View Code
相关文章推荐
- HDU 2822 Dogs【两次bfs】
- HDU 2822 Dogs【两次bfs】
- HDU - 2822 Dogs (优先队列+bfs)
- hdu 2822 Dogs (优先队列 + BFS)
- hdu - 2822 Dogs (优先队列+bfs)
- hdu 2822 Dogs
- HDU 2612 Find a way(两次bfs)
- hdu 2822 Dogs(优先队列)
- hdu 2822 Dogs
- hdu 1973+hdu 2364+hdu 2416+hdu 2822+hdu 2645(bfs)
- Problem N HDU 2612 Find a way (两次BFS求最值)
- hdu 2822 Dogs(优先队列)
- hdu 4514 并查集判断无向图是否有环+树(无环连通图)的直径(两次bfs)
- HDU 2822 Dogs
- HDU 2822 Dogs(优先队列)
- HDU_BFS_2822
- hdu 2822 Dogs【优先队列+Bfs】
- hdu 2822 Dogs
- hdu 2822 Dogs(BFS + 优先队列)
- HDU_1254——推箱子,两次BFS