您的位置:首页 > 其它

Hdu 1072 Nightmare

2012-08-19 12:02 239 查看
简单搜索题,由于很久没写搜索题的缘故,我自己的模板出现了小问题。

注意:1、如果maze[q.x][q.y] == 4的话可能会出现死循环,所以要走过之后直接标记为0。

CODE:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <queue>
using namespace std;

const int SIZE = 110;
int maze[SIZE][SIZE];
const int move[4][2] = {{1, 0}, {-1, 0}, {0, -1}, {0, 1}};
int flag[SIZE][SIZE];
int N, M;
int bx, by;

struct node
{
int x, y;
int step;
int costT;
}p, q;

int check(int r, int c)
{
if(maze[r][c] != 0 && r < N && c < M && r >= 0 && c >= 0)
return 1;
return 0;
}

void bfs(int bx, int by)
{
queue<node> Q;
p.x = bx; p.y = by;
p.step = 6; p.costT = 0;
Q.push(p);
while(!Q.empty())
{
p = Q.front();
Q.pop();
for(int i = 0; i < 4; i++)
{
q = p;
q.x += move[i][0];
q.y += move[i][1];
if(check(q.x, q.y))
{
if(maze[q.x][q.y] == 1)
{
q.step--;
if(q.step > 0)
{
q.costT++;
Q.push(q);
}
}
if(maze[q.x][q.y] == 4)
{
q.step--;
if(q.step > 0)
{
q.costT++;
q.step = 6;
Q.push(q);
}
maze[q.x][q.y] = 0; //可能会有死循环
}
if(maze[q.x][q.y] == 3 && q.step > 1)
{
printf("%d\n", ++q.costT);
return ;
}
}
}
}
printf("-1\n");
return ;
}

int main()
{
int T;
int i, j;
scanf("%d", &T);
while(T--)
{
memset(maze, 0, sizeof(maze));
scanf("%d%d", &N, &M);
for(i = 0; i < N; i++)
{
for(j = 0; j < M; j++)
{
scanf("%d", &maze[i][j]);
if(maze[i][j] == 2)
{
bx = i;
by = j;
}
}
}
bfs(bx, by);
}
return 0;}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: