您的位置:首页 > 其它

hdu 2822 bfs

2015-10-06 09:56 302 查看
问题可以抽象为求起点到终点的最短路,其中经过x的代价是0,而经过.的代价是1,bfs的时候用优先队列即可。

#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;

const int N = 1001;
char maze

;
bool visit

;
int dx[] = { 0, 0, 1, -1 };
int dy[] = { 1, -1, 0, 0 };
int n, m, sx, sy, ex, ey;

bool ok( int x, int y )
{
return x >= 0 && x < n && y >= 0 && y < m && !visit[x][y];
}

struct Node
{
int x, y, t;
Node(){}
Node( int _x, int _y, int _t )
{
x = _x, y = _y, t = _t;
}
bool operator < ( const Node & o ) const
{
return t > o.t;
}
};

priority_queue<Node> q;

int bfs()
{
while ( !q.empty() ) q.pop();
memset( visit, 0, sizeof(visit) );
q.push( Node( sx, sy, 0 ) );
visit[sx][sy] = 1;
while ( !q.empty() )
{
Node cur = q.top();
q.pop();
if ( cur.x == ex && cur.y == ey ) return cur.t;
for ( int i = 0; i < 4; i++ )
{
int x = cur.x + dx[i];
int y = cur.y + dy[i];
if ( ok( x, y ) )
{
int d = maze[x][y] == '.' ? 1 : 0;
q.push( Node( x, y, cur.t + d ) );
visit[x][y] = 1;
}
}
}
return -1;
}

int main ()
{
while ( scanf("%d%d", &n, &m) != EOF )
{
if ( !n && !m ) break;
for ( int i = 0; i < n; i++ )
{
scanf("%s", maze[i]);
}
scanf("%d%d%d%d", &sx, &sy, &ex, &ey);
sx--, sy--, ex--, ey--;
int ans = bfs();
printf("%d\n", ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: