The maze was a rectangle with sizes N by M. There was a door in the maze. At the beginning, the door was closed and it would open at the T-th second for a short period of time (less than 1 second). Therefore the doggie had to arrive at the door on exactly the T-th second. In every second, he could move one block to one of the upper, lower, left and right neighboring blocks. Once he entered a block, the ground of this block would start to sink and disappear in the next second. He could not stay at one block for more than one second, nor could he move into a visited block. Can the poor doggie survive? Please help him.
'X': a block of wall, which the doggie cannot enter;
'S': the start point of the doggie;
'D': the Door; or
'.': an empty block.
The input is terminated with three 0's. This test case is not to be processed.
4 4 5 S.X. ..X. ..XD .... 3 4 5 S.X. ..X. ...D 0 0 0
NO YES
此题的关键是 奇偶剪枝
#include<iostream>
#include<stdio.h>
#include<string>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
int N,M,T;
char array[8][8];
bool Visited[8][8],ans,flag;
int S_X,S_Y,E_X,E_Y;
void DFS(int x,int y,int c)
{
if(flag) return;
if(c > T) return;
if(x < 0||x >= N||y < 0||y >= M)
return;
if(array[x][y] == 'D'&& c == T)
{
ans = flag = true;
return;
}
int temp = abs(x - E_X) + abs(y - E_Y);
temp = T - c - temp;
if(temp % 2 != 0) return;
if(!Visited[x-1][y] && array[x-1][y] != 'X')
{
Visited[x-1][y] = true;
DFS(x-1,y,c+1);
Visited[x-1][y] = false;
}
if(!Visited[x+1][y] && array[x+1][y] != 'X')
{
Visited[x+1][y] = true;
DFS(x+1,y,c+1);
Visited[x+1][y] = false;
}
if(!Visited[x][y-1] && array[x][y-1] != 'X')
{
Visited[x][y-1] = true;
DFS(x,y-1,c+1);
Visited[x][y-1] = false;
}
if(!Visited[x][y+1] && array[x][y+1] != 'X')
{
Visited[x][y+1] = true;
DFS(x,y+1,c+1);
Visited[x][y+1] = false;
}
}
int main()
{
int i,j,k;
while(~scanf("%d%d%d",&N,&M,&T),N||M||T)
{
memset(Visited,false,sizeof(Visited));
int count = 0;
for(i = 0;i < N;i++)
{
for(j = 0;j < M;j++)
{
cin>>array[i][j];
//scanf("%c",array[i][j]);
if(array[i][j] == 'S')
{
S_X = i;
S_Y = j;
Visited[i][j] = true;
}
if(array[i][j] == 'D')
{
E_X = i;
E_Y = j;
}
if(array[i][j] == 'X')
count ++;
}
}
flag = false;
if(N*M - count - 1 >= T)
DFS(S_X,S_Y,0);
if(flag)
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
}
return 0;
}