4 4 5 S.X. ..X. ..XD .... 3 4 5 S.X. ..X. ...D 0 0 0
NO YES
Recommend
TIE了非常多次,总结一下坑点,
1 输入的循环要从1开始。
2 需要进行优化
深搜部分还是挺简单的,剪枝的地方确实难想到,这也是我TIL很多次的原因。
上代码
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
int abs(int a)
{
return a>0?a:-a;
}
int x1,y1;
int n,m,t,ok;
char map[10][10];
int dir[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
void dfs(int x,int y,int w)
{
int sx,sy,i,pp;
if(x<=0 ||y<=0 ||x>n ||y>m )
return;
pp=t-w-abs(x1-x)-abs(y1-y);//剪枝关键的一步。
if(pp<0 ||pp%2)
return;
// 0 1 0 1 0 1 0 1 0
// 1 0 1 0 1 0 1 0 1
// 0 1 0 1 0 1 0 1 0
// 1 0 1 0 1 0 1 0 1
// 0 1 0 1 0 1 0 1 0
// 1 0 1 0 1 0 1 0 1
// 0 1 0 1 0 1 0 1 0
// 1 0 1 0 1 0 1 0 1
// 无论是从o 开始还是从1开始,
// 都是 0--->1 或者1--->0 都是奇数步
// 0-->0 , 1--->1 都是偶数步
if(x==x1 &&y==y1 &&w==t) //满足出来的坐标,并且时间为t,令OK为一。
{
ok=1;
return;
}
for(i=0;i<4;i++)//深搜。
{
sx=x+dir[i][0];
sy=y+dir[i][1];
if(map[sx][sy]!='X')
{
map[sx][sy]='X';
dfs(sx,sy,w+1);
if(ok)
return;
map[sx][sy]='.';
}
}
return;
}
int main()
{
int i,j,x3,y3;
while(scanf("%d%d%d",&n,&m,&t)!=EOF)
{
if(n==0&&n==0 &&t==0)
break;
getchar();
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
{
scanf("%c",&map[i][j]);
if(map[i][j]=='S')
{
x3=i;//进入的坐标
y3=j;
}
else if(map[i][j]=='D')
{
x1=i;//出来的坐标
y1=j;
}
}
getchar();
}
ok=0;
map[x3][y3]='X';//标志已访问过
dfs(x3,y3,0);// 深搜
if(ok)
printf("YES\n");//OK为一则行,反之不行
else
printf("NO\n");
}
return 0;
}
原文地址:http://blog.csdn.net/sky_miange/article/details/43269885