HDU_1072 Nightmare(BFS)
这题用bfs做的,总结出来一条真理!在用bfs时,如果要引用结构体定义中的值,一定加中间变量,不要直接在上边操作。
思路:直接用bfs找终点,如果中途遇到map[i][j] == 4的点,就把time置为6, 把走过的map[i][j] == 4的点标记为0;
My Code:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
struct nightmare
{
int i;
int j;
int t;
int step;
}q[10000];
int d[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
int map[9][9];
int n, m, si, sj;
int bfs(int si, int sj)
{
nightmare p, tmp;
int f = 0, r = 0, i, x, y;
int tt, s;
q[0].i = si;
q[0].j = sj;
q[0].t = 6;
q[0].step = 0;
r++;
while(f < r)
{
p = q[f++];
for(i = 0; i < 4; i++)
{
x = p.i + d[i][0]; //中间变量x, y;
y = p.j + d[i][1];
tt = p.t-1; s = p.step + 1; //中间变量tt, ss;
if(tt <= 0) continue;
if(x >= 0 && x < n && y >= 0 && y < m && map[x][y] != 0)
{
if(map[x][y] == 3) return s;
if(map[x][y] == 4)
{
tt = 6;
map[x][y] = 0;
}
tmp.i = x;
tmp.j = y;
tmp.t = tt;
tmp.step = s;
q[r++] = tmp;
}
}
}
return -1;
}
int main()
{
//freopen("data.in", "r", stdin);
int t, i, j;
cin >> t;
while(t--)
{
cin >> n >> m;
memset(map, 0, sizeof(map));
for(i = 0; i < n; i++)
for(j = 0; j < m; j++)
{
cin >> map[i][j];
if(map[i][j] == 2)
{
si = i; sj = j;
}
}
cout << bfs(si, sj) << endl;
}
return 0;
}