hdu1010 dfs+剪枝

剪枝很巧妙的,對於下標相加爲奇數的點不能在偶數步走到下標相加爲偶數的點,依次類推
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;

char map[10][10];
bool book[10][10];

int to[4][2] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};

int startx, starty, endx, endy;
int N, M, T, flag, temp, s1, s2;

void dfs(int x, int y){
	if(flag){
		return;
	}
	int nowx, nowy;
	if(x == endx && y == endy){
		if(!T)
			flag = 1;
	}
	if(!T){
		return;
	}
	for(int i = 0; i < 4; i++){
		nowx = x + to[i][0];
		nowy = y + to[i][1];
		if(nowx > 0 && nowx <= N && nowy > 0 && nowy <= M){
			if((map[nowx][nowy] == '.' || map[nowx][nowy] == 'D') && !book[nowx][nowy]){
				T--;
				book[x][y] = true;
				dfs(nowx, nowy);
				book[x][y] = false;
				T++;
			}
		}
	}
}
int main(){
	while(scanf("%d %d %d", &N, &M, &T) != EOF){
		temp = -1;
		if(!N || !M || !T){
			return 0;
		}
		getchar();
		flag = 0;
		memset(book, 0, sizeof(book));
		for(int i = 1; i <= N; i++){
			for(int j = 1; j <= M; j++){
				scanf("%c", &map[i][j]);
				if(map[i][j] == 'S'){
					startx = i;
					starty = j;
				}
				if(map[i][j] == 'D'){
					endx = i;
					endy = j;
				}
			}
			getchar();
		}
		
		if(abs(startx-endx)+abs(starty-endy)>T||(startx+endx+starty+endy+T)%2==1)            //剪枝
        {
            printf("NO\n");
            continue;
        }
		dfs(startx, starty);	
		if(flag){
			cout << "YES" << endl;
		}
		else{
			cout << "NO" << endl;
		}
	}
	return 0;
}

發佈了37 篇原創文章 · 獲贊 34 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章