-
题目
-
题意
根据地图,'S'为开始位置,'D'为门的位置,' . '为空地,'X'为墙,不能经过,
问:在指定的时间,是否能到达'门'的位置.
注意:路不可以重复经过,时间也要刚好是 t ,不能少.
-
分析
之前用了BFS,是不对的。
因为使用BFS的话,求得的是最短路径(T时间到终点,且是最短路径)。然而,这一题的路径不一定是最短的。
-
代码
我的奇偶剪枝怎么跟别人 不太一样???
//AC
//HDU 1010 using DFS algorithm
#include<iostream>
#include<algorithm>
#include<queue>
#include<stack>
#include<set>
#include<cstring>
#include<cmath>
using namespace std;
using namespace std;
int nextx[4] = { 0 , 0 , 1 , -1};
int nexty[4] = { 1 , -1 , 0 , 0};
char mp[8][8];
int book[8][8];
int leaststep[8][8];
int N, M , T;
int startx , starty , endx , endy;
int DFS ( int x, int y , int reststep)
{
//cout<<x<<" "<<y<<" ";
if ( x == endx && y == endy && reststep == 0)
{
//cout<<"Y1";
return 1;
}
book[x][y] = 1 ;
for ( int i = 0 ; i < 4 ;i++ )
{
int nx = x + nextx[i];
int ny = y + nexty[i];
//cout<<nx<<" "<<ny<<" ";
if( book[nx][ny] == 1 )
continue;
if (mp[nx][ny] == 'X')
continue;
if ( nx > N || nx <= 0 || ny > M || ny <= 0 )
{
continue;
}
if(reststep == 0 )
continue;
// cout<<nx<<" "<<ny<<" "<<reststep <<endl;
book[nx][ny] = 1; //前后都有标记
if (T - reststep - (abs(endx - nx) + abs(endy - ny)) & 1) continue; //不加会T
//如果
if(DFS( nx , ny , reststep - 1))
return 1;
book[nx][ny] = 0; //是为了回溯
}
return 0;
}
int main()
{
while(scanf("%d%d%d" , &N , &M , &T) !=EOF)
{
if(N == 0 && M == 0 && T == 0)
{
break;
}
for (int i = 1 ; i <=N ; i++)
{
for ( int j =1 ; j <=M ; j++)
{
cin>>mp[i][j];
if( mp[i][j] == 'S')
{
startx = i;
starty = j;
}
if ( mp[i][j] == 'D')
{
endx = i;
endy = j;
}
}
}
memset(book , 0 ,sizeof(book));
book[startx][starty] = 1;
/*
for (int i =1; i<=M ;i++)
{
for( int j =1;j <=N ;j++)
cout<<leaststep[i][j];
cout<<endl;
}*/
if ( DFS( startx , starty , T))
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
}
}
/*
if ( x > N || x <= 0 || y > M || y <= 0 )
{
cout<<x<<" "<<y<<" ";
cout<<"N1";
return 0;
}
if (reststep == 0 )
{
cout<<x<<" "<<y<<" ";
cout<<"N2";
return 0;
}
if ( book[x][y] == 1 )
{
cout<<x<<" "<<y<<" ";
cout<<"N3";
return 0;
}
if ( mp[x][y] != '.' || mp[x][y] == 'S')
{
cout<<x<<" "<<y<<" ";
cout<<"N4";
return 0;
}
*/