hdu 1010 Tempter of the Bone dfs+奇偶性剪枝

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;

int n,m,t;
char map[8][8];
int book[8][8]; 
int startx,starty;
int endx,endy;
int judge;
int next1[4][2]={{0,1},{1,0},{-1,0},{0,-1}};

void dfs(int row,int col,int step)
{
	if(step > t)  return ;//步数大于时间
	if(((t-step)%2 != (abs(row-endx) + abs(col-endy)) %2)) return;//奇偶剪枝 
    if(t-step-abs(row-endx)-abs(col-endy)<0) return;//步数不够剪枝
    
	if(map[row][col] == 'D' && step==t) 
	{
			judge = 1;return ;
	}
		
	for(int k = 0;k < 4;++k)
	{
		int tx = row+next1[k][0];
		int ty = col+next1[k][1];
		if(tx < 1 || tx > n || ty < 1 || ty > m) continue;		     
		if(!book[tx][ty] && !judge) //judge用来判断是否已准时到达,若到达,则全部回溯,不用在递归
		{
			book[tx][ty] = 1;
			dfs(tx,ty,step+1);
			book[tx][ty] = 0;
		}		    
	}
}

int main()
{
	while(scanf("%d%d%d",&n,&m,&t)&&n&&m&&t)
	{
		judge = 0; 
		memset(book,0,sizeof(book));
		for(int i = 1;i <= n;++i)
		   for(int j = 1;j <= m;++j)
		      {
		      	 cin >> map[i][j];
		      	 if(map[i][j] == 'S')
		      	     startx=i,starty=j;
		      	 if(map[i][j] == 'D')
		      	     endx=i,endy=j;
		      	 if(map[i][j] == 'X')  
		      	     book[i][j] = 1;
		      }
		book[startx][starty] = 1;
		dfs(startx,starty,0); 
		if(judge)
		   cout << "YES" << endl;
		else
		   cout << "NO" << endl;
	}
	return 0;
}

剪枝方法:奇偶剪枝

                             把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 需要奇数步

                       从 0->0 需要偶数步
                       那么设所在位置 (x,y) 与 目标位置 (dx,dy)

                       如果abs(x-y)+abs(dx-dy)为偶数,则说明 abs(x-y) 和 abs(dx-dy)的奇偶性相同,需要走偶数步

                       如果abs(x-y)+abs(dx-dy)为奇数,那么说明 abs(x-y) 和 abs(dx-dy)的奇偶性不同,需要走奇数步

                       理解为 abs(si-sj)+abs(di-dj) 的奇偶性就确定了所需要的步数的奇偶性!!

                       而 (t-setp)表示剩下还需要走的步数,由于题目要求要在 t时 恰好到达,那么  (t-step) 与 abs(x-y)+abs(dx-dy) 的奇偶性必须相同

                       因此 temp=t-step-abs(dx-x)-abs(dy-y) 必然为偶数!

猜你喜欢

转载自blog.csdn.net/qq_40511966/article/details/82930777