您的位置:首页 > 其它

HDU 1242 简单bfs

2012-09-08 10:25 316 查看
#include <iostream>
#include <queue>
using namespace std;
int n, m;
const int MAX = 205;
char a[MAX][MAX], map[MAX][MAX];
int dir[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
struct node
{
int x, y, step;
};
void bfs()
{
int i, j;
struct node cur, next, end;
for(i = 0; i < n; i++)
for(j = 0; j < m; j++)
{
if(a[i][j] == 'r')
{
cur.x = i;
cur.y = j;
cur.step = 0;
}
if(a[i][j] == 'a')
{
end.x = i;
end.y = j;
}
}

if(cur.x == end.x && cur.y == end.y)
{
cout << 0 << endl;
return;
}

queue<node> q;
q.push(cur);
while(!q.empty())
{
cur = q.front();
q.pop();
for(i = 0; i < 4; i++)
{
next.x = cur.x + dir[i][0];
next.y = cur.y + dir[i][1];
next.step = cur.step + 1;
if(next.x == end.x && next.y == end.y)
{
cout << next.step << endl;
return;
}
if(next.x >= 0 && next.x < n && next.y >= 0 && next.y < m && map[next.x][next.y] == 0)
{
map[next.x][next.y] = 1;
if(a[next.x][next.y] == 'x')
next.step += 1;
if(a[next.x][next.y] == '#')
continue;
q.push(next);
}
}
}
cout << "Poor ANGEL has to stay in the prison all his life." << endl;
}
int main()
{
int i, j;
while(scanf("%d%d", &n, &m) != EOF)
{
memset(map, 0, sizeof(map));
for(i = 0; i < n; i++)
scanf("%s", a+i);
bfs();
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: