
1 6 6 2 ...Y.. ...#.. .#.... ...#.. ...#.. ..#G#.
7
给定一个R*C的图,求起点到终点的最小步数。要求不能经过障碍物,障碍物在K的整数倍的时候会暂时消失。
简单三维的BFS,这个题目因为要判断步数是不是K的整数倍。当下一步的某个位置为障碍物的时候,我们不能直接跳过这个障碍物,因为存在先到其他点,然后在K的整数倍的时候刚好到达这个点的情况,也就是样例的情况。由此可见,必须要三维才能准确地描述状态。另开一维用来描述(i, j)这个点在对K取模这一状态是否被访问过即可。
#include <queue>
#include <cstdio>
#include <string>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define FIN freopen("input.txt","r",stdin)
#define CASE(T) int T;for(scanf("%d",&T);T--;)
const int maxn = 100 + 5;
const int INF = 0x3f3f3f3f;
const int dir[4][2] = { -1,0, 1,0, 0,1, 0,-1 };
int R, C, K, ans;
char Map[maxn][maxn];
bool vis[maxn][maxn][15];
struct Node
{
int x, y, step;
Node() {}
Node(int _x, int _y, int _s) : x(_x), y(_y), step(_s) { }
} Now;
queue<Node> Que;
void Read_Graph();
void Solve();
int main()
{
// FIN;
CASE(T)
{
Read_Graph();
Solve();
}
return 0;
}
void Read_Graph()
{
scanf("%d %d %d", &R, &C, &K);
for(int i = 0; i < R; i++)
{
scanf("%s", Map[i]);
for(int j = 0; j < C; j++)
{
if(Map[i][j] == 'Y')
Now = Node(i, j, 0);
}
}
}
inline bool InRange(int x, int y)
{
return x >= 0 && x < R && y >= 0 && y < C;
}
void Solve()
{
ans = INF;
memset(vis, false, sizeof(vis));
Que.push(Now);
vis[Now.x][Now.y][0] = true;
while(!Que.empty())
{
Now = Que.front();
Que.pop();
if(Map[Now.x][Now.y] == 'G')
{
ans = min(ans, Now.step);
continue;
}
for(int i = 0; i < 4; i++)
{
int xx = Now.x + dir[i][0], yy = Now.y + dir[i][1], ss = Now.step + 1;
if(InRange(xx, yy) && !vis[xx][yy][ss % K] && ss <= ans)
{
if(Map[xx][yy] == '#' && ss % K != 0) continue;
Que.push(Node(xx, yy, ss));
vis[xx][yy][ss % K] = true;
}
}
}
if(ans >= INF)
printf("Please give me another chance!\n");
else printf("%d\n", ans);
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
hdu 2579 Dating with girls(2) 【经典三维BFS】
原文:http://blog.csdn.net/acmore_xiong/article/details/48096183