首页 > 其他 > 详细

hdu 1010 DFS + 剪枝

时间:2015-04-24 10:39:22      阅读:214      评论:0      收藏:0      [点我收藏+]
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <queue>
#include <stack>
#include <climits>
#include <cstring>
#include <cmath>
#include <map>
#include <set>

using namespace std;
int n,m,t;
int vx[][2] = {{0,1},{1,0},{-1,0},{0,-1}};
struct node{
	int x,y;
};
char a[10][10];
int ans;
int flag[10][10];


void dfs(node s,int step){
	node v;
	if(ans) return;	
	if(a[s.x][s.y] == 'D' && step == t){
		ans = 1;
		return ;
	}
	if(step >= t)
		return;
	for(int i = 0;i < 4;i++){
		v.x = s.x + vx[i][0];
		v.y = s.y + vx[i][1];
	
		if(a[v.x][v.y] != 'X' && !flag[v.x][v.y]){
			flag[v.x][v.y] = 1;
			dfs(v,step+1);
			flag[v.x][v.y] = 0;
			if(ans) return;
		}
	}
} 

int main(){
	for(int i = 0;i <= 7+1;i++){
		for(int j = 0;j <= 7+1;j++){
			a[i][j] = 'X';
		}
	}
	//freopen("未命名4.cpp","r",stdin);
	while(scanf("%d%d%d",&n,&m,&t),n||m||t){
		getchar();
		node s,e;
		 
		for(int i = 1;i <= n;i++){
			for(int j = 1;j <= m;j++){
				a[i][j] = getchar();
				if(a[i][j] == 'S'){
					s.x = i;
					s.y = j;
				}
				if(a[i][j] == 'D'){
					e.x = i;
					e.y = j;
				}
			}	
			getchar();
		}
		
		if(abs(s.x-e.x) + abs(s.y - e.y) > t || (s.x + s.y + e.x + e.y + t) % 2 == 1){ //判断狗到终点的曼哈顿距离是否大于t,和狗走到终点的位置是用的步数奇偶性是否相同
" << endl;;
			continue;
		}
		ans = 0;
		memset(flag,0,sizeof(flag));
		flag[s.x][s.y] = 1;
		
		dfs(s,0);
		
		if(ans){
			cout << "YES" << endl;
		}
		else{
			cout << "NO" << endl;
		}
	}	 
	return 0;
}


hdu 1010 DFS + 剪枝

原文:http://blog.csdn.net/qq_24667639/article/details/45242211

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!