题目:http://acm.hdu.edu.cn/showproblem.php?pid=1010
奇偶性剪枝
可以把map看成这样:
0 1 0 1 0 1
1 0 1 0 1 0
0 1 0 1 0 1
1 0 1 0 1 0
0 1 0 1 0 1
从为0的格子走一步,必然走向为1的格子,从为1的格子走一步,必然走向为0的格子。
即:
0 ->1或1->0 必然是奇数步
0->0 走1->1 必然是偶数步
所以当遇到从0走向0但是要求时间是奇数的,或者从1走向0但是要求时间是偶数的都可以直接判断不可达!
#include <iostream>
#include <string.h>
#include <algorithm>
#include <stdio.h>
using namespace std;
const int N = 15;
char map[N][N];
int startx,starty,endx,endy;
int n,m,Time;
bool flag;
int dir[4][2] = {-1,0,1,0,0,-1,0,1};
void DFS(int x,int y,int t)
{
if(flag) return;
if(x == endx && y == endy && t == Time)
{
flag = 1;
return;
}
int tmp = abs(x - endx) + abs(y - endy);
if((Time - t) % 2 != tmp % 2) return;
if(tmp > Time - t) return;
for(int i=0;i<4;i++)
{
int tx = x + dir[i][0];
int ty = y + dir[i][1];
if(tx < n && tx >= 0 && ty < m && ty >= 0 && map[tx][ty] != 'X')
{
map[tx][ty] = 'X';
t++;
DFS(tx,ty,t);
t--;
map[tx][ty] = '.';
}
}
}
int main()
{
while(cin>>n>>m>>Time)
{
if(n == 0 && m == 0 && Time == 0) break;
int cnt = 0;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
cin>>map[i][j];
if(map[i][j] == 'S')
{
startx = i;
starty = j;
map[i][j] = 'X';
}
else if(map[i][j] == 'D')
{
endx = i;
endy = j;
}
else if(map[i][j] == '.') cnt++;
}
}
if(cnt + 1 < Time)
{
puts("NO");
continue;
}
flag = false;
DFS(startx,starty,0);
if(flag) puts("YES");
else puts("NO");
}
return 0;
}