您的位置:首页 > 其它

hdu 3345 bfs

2012-11-03 09:39 134 查看
#include <stdio.h>
#include <string.h>
#include <queue>
using namespace std;

const int M = 105;

int n, m, mv;
char mp[M][M], ans[M][M];
int flg[M][M];
int s[2];
int dir[4][2] = {-1,0, 0,1, 1,0, 0,-1};

struct node
{
int x, y, v;
};
queue<node> qu;

int in(int x, int y)
{
return x >= 0 && x < n && y >= 0 && y < m;
}

int cal(int x, int y, int v)
{
int i, nx, ny, ret;

if (mp[x][y] == 'T')
ret = v - 2;
else if (mp[x][y] == 'R')
ret = v - 3;
else
ret = v - 1;

for (i = 0; i < 4; i++)
{
nx = x + dir[i][0];
ny = y + dir[i][1];
/*注意,return时 ret > 0, 才变为0,表示可到
ret < 0, 本来就不可到,不可以变成0(0表示可到)
*/
if (in(nx, ny) && mp[nx][ny] == 'E')
return ret > 0 ? 0 : ret;
}

return ret;
}

void bfs()
{
int i, j;
node p, q;
p.x = s[0];
p.y = s[1];
p.v = mv;
qu.push(p);
flg[s[0]][s[1]] = mv;
ans[s[0]][s[1]] = 'Y';

while (!qu.empty())
{
p = qu.front();
qu.pop();

if (p.v == 0) continue;
for (i = 0; i < 4; i++)
{
q.x = p.x + dir[i][0];
q.y = p.y + dir[i][1];
if (!in(q.x, q.y)) continue;
if (mp[q.x][q.y] == 'Y' ||mp[q.x][q.y] == 'E' || mp[q.x][q.y] == '#')
continue;
q.v = cal(q.x, q.y, p.v);
if (q.v < 0) continue;

if (q.v > flg[q.x][q.y])
{
flg[q.x][q.y] = q.v;
qu.push(q);

if (mp[q.x][q.y] != 'P')
ans[q.x][q.y] = '*';
}
}
}
int main()
{
int i, j, tt, tag;
char ch;

scanf ("%d", &tt);
while (tt--)
{
scanf (" %d %d %d", &n, &m, &mv);
scanf ("%c", &ch);
memset(flg, -1, sizeof(flg));

tag = 0;
for (i = 0; i < n; i++)
{
gets(mp[i]);
for (j = 0; j < m; j++)
{
if (mp[i][j] == 'Y')
{
s[0] = i, s[1] = j;
}
ans[i][j] = mp[i][j];
}
ans[i][m] = '\0';
}

bfs();

for (i = 0; i < n; i++)
{
printf ("%s\n", ans[i]);
}

printf ("\n");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: