原题
http://acm.hdu.edu.cn/showproblem.php?pid=1010
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <ctype.h>
#include <malloc.h>
#include <string.h>
#include <algorithm>
#include <iostream>
#include <string>
#include <stack>
#include <queue>
#include <deque>
#include <vector>
#include <map>
using namespace std;
int n,m,t;
char a[9][9];
int di,dj;//终点
int help[4][2]={{0,-1},{0,1},{1,0},{-1,0}};
int flag;
void DFS(int si,int sj,int cnt){
int i,tmp;
if(si<=0 || si>n || sj<=0 || sj>m){//这个判断一直写错。。。。。。
return ;
}
if(si==di && sj==dj && cnt==t){
flag = 1;
return;
}
tmp = abs(t-cnt)-(abs(si-di)+abs(sj-dj));//剪枝
if(tmp<0 || tmp&1){//如果少了后面这个就会超时,假设图中每个点的坐标相加如果是奇数,则为0,否则为1.如果从奇数点走到奇数点,则步数必为奇数
return ;//如果从偶数点走到偶数点,则步数必为偶数,所以当前剩下的必须是偶数才行。
}
for(i=0;i<4;i++){
if(a[si+help[i][0]][sj+help[i][1]]!='X'){
a[si+help[i][0]][sj+help[i][1]]='X';
DFS(si+help[i][0],sj+help[i][1],cnt+1);
if(flag)
return ;
a[si+help[i][0]][sj+help[i][1]]='.';
}
}
}
int main(){
int i,j;
int si,sj;
int count;
while(~scanf("%d%d%d",&n,&m,&t)){
if(n==0 && m==0 && t==0)
break;
for(i=1;i<=n;i++){
scanf("%s",a[i]+1);
}
count = 0;
for(i=1;i<=n;i++){
for(j=1;j<=m;j++){
if(a[i][j]=='S'){
si = i;
sj = j;
}
if(a[i][j] == 'D'){
di = i;
dj = j;
}
if(a[i][j] == 'X'){
count++;
}
}
}
if(n*m-count <= t){//剪枝,优化
printf("NO\n");
continue;
}
a[si][sj] = 'X';
flag = 0;
DFS(si,sj,0);
if(flag == 1){
printf("YES\n");
}
else{
printf("NO\n");
}
}
return 0;
}