hdu1010 dfs+剪枝

来源:互联网 发布:手机移动数据怎么关闭 编辑:程序博客网 时间:2024/05/16 16:11
剪枝很巧妙的,对于下标相加为奇数的点不能在偶数步走到下标相加为偶数的点,依次类推
#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;}

0 0
原创粉丝点击