您的位置:首页 > 其它

hdu 1072 Nightmare (广搜)

2014-02-02 20:53 453 查看
/*

题意: 2为起点,3为终点,开始时间为6,没走一步减1; 遇到4时重新计时,可重复走。

解题:就是普通的广搜,唯一不同的是路可重复走,将标记是否走过的mark数组,标记为走过一次加1,每一个位子最多可走8次即可。

*/

#include<iostream>
#include<queue>
using namespace std;
int n, m, s[10][10], mark[10][10], dir[4][2] = {1,0, 0,1, -1,0, 0,-1};
int flag, s_x, s_y, e_x, e_y;

struct node
{
int x, y, step;
int flag_step;
};

int judge(int x, int y)
{
if(x>=0 && x<n && y>=0 && mark[x][y]<8 && s[x][y] != 0)
return 1;
else
return 0;
}

int bfs()
{
int i;
queue<node>q;
node cur, next;
cur.x=s_x; cur.y=s_y; cur.step=0;
cur.flag_step=0;
q.push(cur);
while(!q.empty())
{
cur = q.front();
q.pop();
if(cur.x==e_x && cur.y==e_y) return cur.step;
if(cur.flag_step == 5) continue;
for( i=0; i < 4; i++ )
{
next.x = cur.x + dir[i][0];
next.y = cur.y + dir[i][1];
if(judge(next.x, next.y))
{
mark[next.x][next.y] += 1;
next.step = cur.step+1;
next.flag_step = cur.flag_step+1;
if(s[next.x][next.y] == 4)
next.flag_step = 0;
q.push(next);
}
}
}
return -1;
}

int main()
{
int T;
scanf("%d", &T);
while(T--)
{
int i, j;
scanf("%d%d", &n, &m);
for( i=0; i < n; i++ )
for(j=0; j < m;j++ )
{
scanf("%d", &s[i][j]);
if(s[i][j] == 2)
s_x=i, s_y=j;
if(s[i][j] == 3)
e_x=i, e_y=j;
}

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