可怜的公主在一次次被魔王掳走一次次被骑士们救回来之后,而今,不幸的她再一次面临生命的考验。魔王已经发出消息说将在T时刻吃掉公主,因为他听信谣言说吃公主的肉也能长生不老。年迈的国王正是心急如焚,告招天下勇士来拯救公主。不过公主早已习以为常,她深信智勇的骑士LJ肯定能将她救出。
现据密探所报,公主被关在一个两层的迷宫里,迷宫的入口是S(0,0,0),公主的位置用P表示,时空传输机用#表示,墙用表示,平地用.表示。骑士们一进入时空传输机就会被转到另一层的相对位置,但如果被转到的位置是墙的话,那骑士们就会被撞死。骑士们在一层中只能前后左右移动,每移动一格花1时刻。层间的移动只能通过时空传输机,且不需要任何时间。
Input
输入的第一行C表示共有C个测试数据,每个测试数据的前一行有三个整数N,M,T。 N,M迷宫的大小NM(1 <= N,M <=10)。T如上所意。接下去的前NM表示迷宫的第一层的布置情况,后NM表示迷宫第二层的布置情况。
Output
如果骑士们能够在T时刻能找到公主就输出“YES”,否则输出“NO”。
Sample Input
1
5 5 14
S*#*.
.#…
…
****.
…#.
….P
#.…
**…
….
*.#…
Sample Output
YES
第一次接触双层深搜,这题是看了别人的题解后还搞了很久很久,看完题解自己写一遍后一直ac不了,拿着别人的代码一遍遍在那查哪里不一样,越改越跟别人的代码接近相同。该题在记录走过的时候要特别小心,选一条路线后,走过的点要记录,但切记这条路线走完要给他把记录消除,因为别的路线也可以经过。但一条路线走超过给定的时间,就不必要再走了,任一一条路线在时间t内(注意是t内)走到P也就没必要再走了。
ac代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
int fx[4][2] = { 0,1,0,-1,1,0,-1,0 };
int times, m, n, t, low, a, b, ji = 0, cha1[15][15], cha2[15][15];
char p1[15][15], p2[15][15];
void dfs1(int, int, int);
void dfs2(int, int, int);
int asd(int xx, int yy)
{
return(abs(xx - a) + abs(yy - b));
}
void dfs1(int x1, int y1, int step)
{
if (step > t || ji)
return;
if (step + asd(x1, y1) > t&&low == 1)
return;
if (p1[x1][y1] == 'P')
{
ji = 1; return;
}int c, d;
for (int i = 0; i < 4; i++)
{
c= x1 + fx[i][0];
d = y1 + fx[i][1];
if (c >= 0 && d >= 0 && c < n&&d < m &&p1[c][d] != '*' && !cha1[c][d])
{
cha1[c][d] = 1;
if (p1[c][d] == '*')continue;
if (p1[c][d] == '#')
{
if (p2[c][d]!= '#' && p2[c][d] != '*')
dfs2(c, d, step + 1);
}
else dfs1(c, d, step + 1);
cha1[c][d] = 0;
}
}return;
}
void dfs2(int x2, int y2, int step)
{
if (step > t || ji)
return;
if (step + asd(x2, y2) > t&&low == 2)
return;
if (p2[x2][y2] == 'P')
{
ji = 1; return;
}int c, d;
for (int i = 0; i < 4; i++)
{
c = x2 + fx[i][0];
d = y2 + fx[i][1];
if (c >= 0 && d >= 0 && c < n&&d < m &&p2[c][d] != '*' && !cha2[c][d])
{
cha2[c][d] = 1;
if (p2[c][d] == '#')
{
if (p1[c][d] != '#' && p1[c][d] != '*')
dfs1(c, d, step + 1);
}
else dfs2(c, d, step + 1);
cha2[c][d] = 0;
}
}return;
}
int main()
{
int c;
cin >> c;
while (c--)
{
memset(cha1, 0, sizeof(cha1));
memset(cha2, 0, sizeof(cha2));
cha1[0][0] = 1;
cin >> n >> m >> t;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cin >> p1[i][j];
if (p1[i][j] == 'P')
{
low = 1; a = i; b = j;
}
}
} for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cin >> p2[i][j];
if (p2[i][j] == 'P') {
low = 2;
a = i; b = j;
}
}
}ji = 0;
dfs1(0, 0, 0);
if (ji)cout << "YES" << endl;
else cout << "NO" << endl;
}
}