您的位置:首页 > 其它

hdu1010 dfs+剪枝

2016-11-20 15:40 295 查看
剪枝很巧妙的,对于下标相加为奇数的点不能在偶数步走到下标相加为偶数的点,依次类推
#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  dfs poj