嗯....这题我交了27次QAQ
剪枝剪枝剪枝,重要的事情说三遍!奇偶剪枝是很重要的然后各种初始化和return也一定要写,回溯的时候记得还原修改为'X'的路径。
说到底还是我太弱了....
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
int n,m,t,di,dj;
bool ok;
int dr[4][2] = {{1,0},{-1,0},{0,1},{0,-1}};
char a[10][10];
void dfs(int x, int y, int cnt)
{
if (x==di && y==dj && cnt==t)
{
ok = true;
return;
}
if (ok)
return;
if (x<1 || y<1 || x>n || y>m)
{
return;
}
int temp = abs(t-cnt) - abs(x-di) -abs(y-dj);
if (temp<0 || temp%2!=0) // jioujianzhi
{
return;
}
int bi,bj;
bi = bj = 0;
for (int i=0; i<4; i++)
{
bi = x + dr[i][0];
bj = y + dr[i][1];
if (a[bi][bj] != 'X')
{
a[bi][bj] = 'X';
dfs(bi,bj,cnt+1);
a[bi][bj] = '.';
}
}
return;
}
int main()
{
while (cin >> n >> m >> t)
{
int w = 0;
memset(a,'X',sizeof(a));
int si,sj;
si = sj = 0;
if (n==0 && m==0 && t==0)
{
break;
}
for (int i=1; i<=n; i++)
{
scanf("%s",&a[i][1]);
getchar();
for (int 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')
{
w++;
}
}
}
if (n*m-w <= t) //jianzhi
{
printf("NO\n");
continue;
}
a[si][sj] = 'X';
dfs(si,sj,0);
if (ok)
printf("YES\n");
else
printf("NO\n");
ok = false;
}
return 0;
}