HDU_1010_Tempter of the Bone

来源:互联网 发布:mysql 存储手机号 编辑:程序博客网 时间:2024/06/16 13:37

HDU 1010

题意:给定T秒,问是否能在T秒内逃出迷宫,每移动一步就花费一秒钟,已经走过的格子不能再走。思路:用dfs遍历确定能否找到符合条件的路,这里要用到剪枝去优化。
#include <iostream>#include <iomanip>#include <cstring>#include <cstdio>#include <cstdlib>#include <cmath>#include <set>#include <map>#include <list>#include <stack>#include <deque>#include <queue>#include <vector>#include <algorithm>#include <functional>#define PI acos(-1.0)#define eps 1e-10#define INF 0x7fffffff#define debug(x) cout << "--------------> " << x << endltypedef long long LL;typedef unsigned long long ULL;using namespace std;int n, m, t, di, dj //row, column, time, row of destination, column of destinationint vis[10][10], flag, ans, wall;int dx[] = {1, 0, -1, 0}, dy[] = {0, 1, 0, -1};char graph[10][10];void dfs(int x, int y,int cnt){     if(flag || cnt > t) return ;     if(x >= n || y >= m || x < 0 || y < 0)        return ;     if(graph[x][y] == 'D' && cnt == t)     {             flag = 1;             ans = 1;             return ;     }     int tmp = t - cnt - abs(x - di) - abs(y - dj);     if(tmp & 1) return ;      //奇偶剪枝,只有当tmp为偶数才有可能到达     for(int i = 0; i < 4; ++i)     {             int xx = x + dx[i], yy = y + dy[i];             if(!vis[xx][yy] && graph[xx][yy] != 'X')             {                     vis[xx][yy] = 1;                     dfs(xx, yy, cnt+1);                     vis[xx][yy] = 0;             }     }}int main(){        int x,y;        while (scanf("%d%d%d", &n, &m, &t) && n+m+t)        {               memset(vis,0,sizeof(vis));               wall = 0;               for(int i = 0; i < n; ++i)               {                       for(int j = 0; j < m; ++j)                       {                               scanf(" %c",&graph[i][j]);                               if(graph[i][j] == 'S')                               {                                x = i;                                y = j;                                vis[i][j] = 1;                               }                                else if(graph[i][j] == 'D')                                {                                di = i;                                dj = j;                                }                                else if(graph[i][j] == 'X')                                        wall++;                       }               }               ans = 0; flag = 0;               if(n*m-wall-1 >= t)        //优化,可走的步数大于等于t才dfs               dfs(x, y, 0);               ans ? puts("YES") : puts("NO");        }        return 0;}
0 0