1. 程式人生 > >hdu 1010 Tempter of the Bone dfs+奇偶性剪枝

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) 必然為偶數!