HDOJ 2102 A计划(bfs)

时间:2024-01-07 08:25:26

题目链接http://acm.hdu.edu.cn/showproblem.php?pid=2102

思路分析:

<1>搜索方法分析:由于需要寻找最短的找到公主的路径,所以采用bfs搜索

<2>需要注意的地方:

1)如果当前状态为'#'字符,需要传送到另外一层,但是从该层到另外一层的时间是不会计算;

2)如果当前状态为'#'字符,则应该考虑该状态能否拓展;因为另一层的相同位置的字符可能为

'S','P','.','*'或者'#',所以对于另一层相同位置的字符可能的各种情况应该考虑到并处理;

只有当字符为’P’或者’.’时才能被传送,其他字符不能传送,即该状态不能拓展,需要被剪枝;

PS:由于没有考虑到另一层的各种情况,导致WA多次,希望引以为鉴。

代码如下:

#include <iostream>
#include <queue>
#include <cstdio>
#include <cstring>
using namespace std; const int MAX_N = + ;
char maze[][MAX_N][MAX_N];
bool visited[][MAX_N][MAX_N];
int N, M, T;
int move_[][] = {{-, }, {, }, {, -}, {, }}; struct Node
{
int x, y, z;
int time;
Node() { x = y = z = time = ; }
Node(int i, int j, int k, int t) { x = i; y = j; z = k; time = t; }
}; int Bfs()
{
Node start;
queue<Node> state; state.push(start);
visited[][][] = true;
while (!state.empty())
{
int x, y, z, t;
Node temp_state; temp_state = state.front();
state.pop();
x = temp_state.x;
y = temp_state.y;
z = temp_state.z;
t = temp_state.time;
for (int i = ; i < ; ++i)
{
char maze_ch = maze[z][x][y];
int next_x = x + move_[i][];
int next_y = y + move_[i][];
int next_z = z;
int next_time = t + ;
char maze_n_ch = maze[next_z][next_x][next_y]; if (next_x < || next_x >= N || next_y < || next_y >= M
|| next_time > T || visited[next_z][next_x][next_y])
continue;
if (maze_n_ch == '#')
next_z = - next_z;
maze_n_ch = maze[next_z][next_x][next_y];
if (maze_n_ch == '*' || maze_ch == '#')
continue;
if (maze_n_ch == 'P')
return next_time;
Node next_state(next_x, next_y, next_z, temp_state.time + );
state.push(next_state);
visited[next_z][next_x][next_y] = true;
}
}
return -;
} int main()
{
int case_times; scanf("%d", &case_times);
while (case_times--)
{
int ans = ; scanf("%d %d %d", &N, &M, &T);
for (int i = ; i < ; ++i)
for (int j = ; j < N; ++j)
scanf("%s", maze[i][j]);
memset(visited, , sizeof(visited));
ans = Bfs();
if (ans == -)
printf("NO\n");
else
printf("YES\n");
}
return ;
}