您的位置:首页 > 产品设计 > UI/UE

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: