priority_queue+BFS
2011-05-30 19:57
288 查看
//题意: row*col的图, ‘X ’代表可行走, ‘.’代表不能走,输入起始位置和终止位置,如果相邻的不是‘X’,要将‘.’处理掉 , 变成‘X’,求出从起始点到终止点的最少处理‘.’的数 //要用优先级队列 将最少处理的顶点放在队头 #include<iostream> #include<queue> using namespace std; // Accepted 1006 546 MS 12460 KB Visual C++ const int maxn = 1001; int x[] = {0,0,1,-1}; int y[] = {1,-1,0,0}; int g[maxn][maxn]; bool mp[maxn][maxn]; int row , col; struct Node { int x,y; Node(){}; Node(int _x,int _y) : x(_x), y(_y) {}; bool operator == (const Node o) { return x==o.x && y==o.y; } }; inline bool operator < (const Node a,const Node b) { return g[a.x][a.y] > g[b.x][b.y]; } bool check(int sx, int sy) { if(sx>=1 && sx<=row && sy>=1 && sy<=col) return true; return false; } int bfs(int sx, int sy, int ex, int ey) { priority_queue<Node> Q; while(!Q.empty()) Q.pop(); memset(g, -1, sizeof(g)); g[sx][sy] = 0; Q.push(Node(sx, sy)); while(!Q.empty()) { Node now = Q.top(); Q.pop(); if(now == Node(ex, ey)) break; for(int i=0; i<4; i++) { Node next; next.x = now.x + x[i]; next.y = now.y + y[i]; if(check(next.x, next.y) && g[next.x][next.y]==-1) { if(mp[next.x][next.y]) { g[next.x][next.y] = g[now.x][now.y]; } else { g[next.x][next.y] = g[now.x][now.y] + 1; } Q.push(next); } } } return g[ex][ey]; } int main() { int sx, sy, ex, ey; while(scanf("%d%d/n",&row, &col) && row) { for(int i=1; i<=row; i++) { for(int j=1; j<=col; j++) { mp[i][j] = getchar()=='X'; } getchar(); } scanf("%d%d/n%d%d/n",&sx, &sy, &ex, &ey); int ret = bfs(sx, sy, ex, ey); printf("%d/n", ret); } return 0; }
相关文章推荐
- POJ 2312Battle City(BFS-priority_queue 或者是建图spfa)
- hdu 1026 Ignatius and the Princess I(bfs+priority_queue)
- poj 3377(bfs+priority_queue)
- hdu 1242 bfs+priority_queue
- HLG 1613 迷宫问题 (BFS + priority_queue)
- Ignatius and the Princess I hdu 1026 priority_queue + bfs (vector)
- POJ_2312_BFS:priority_queue -- Battle City
- HDOJ 1242 BFS+priority_queue
- POJ_2312_BFS:priority_queue -- Battle City
- 蛇与梯子游戏 (BFS + priority_queue)
- HDU 1242 Rescue (bfs + priority_queue)
- hdoj1242(bfs+priority_queue)
- hdu 1026 Ignatius and the Princess I (bfs+记录路径)(priority_queue)
- priority_queue与bfs不得不说的古寺
- hdu 2680Choose the best route 最短路(加入一个0点) BFS + priority——queue
- nyoj 483 Nightmare 【BFS + priority_queue】
- poj 2312(bfs+priority_queue)
- hdu 1026 Ignatius and the Princess I(bfs+priority_queue)
- PriorityQueue 原理与应用
- PriorityQueue and Heap