HDU 1010 迷宫问题

来源:互联网 发布:苹果mac mini键盘设置 编辑:程序博客网 时间:2024/05/10 00:52
DFS:
剪枝(转):
1:能够走的blocks数小于时间。
2:奇偶性剪枝:
可以把map看成这样:
0 1 0 1 0 1
1 0 1 0 1 0
0 1 0 1 0 1
1 0 1 0 1 0
0 1 0 1 0 1
从为 0 的格子走一步,必然走向为 1 的格子
从为 1 的格子走一步,必然走向为 0 的格子 
即: 
 0 ->1或1->0 必然是奇数步 
 0->0 走1->1 必然是偶数步
 
所以当遇到从 0 走向 0 但是要求时间是奇数的,

或者, 从 1 走向 0 但是要求时间是偶数的 都可以直接判断不可达!


#include<iostream>#include<math.h>using namespace std;char map[10][10];int N,M,T;int di,dj,escape;int dir[4][2]={{0,-1},{0,1},{1,0},{-1,0}};void dfs(int x,int y,int cnt){if(x>N || y>M || x<1 || y<1 )return;if(cnt==T && x==di && y==dj)escape=1;if(escape==1)return;int temp = (T-cnt) - abs(x-di) - abs(y-dj); if(temp<0 || temp &1) //判断奇偶,剪枝return; for(int i=0;i<4;i++) //四个方向,堵住回去的路{if(map[x+dir[i][0]][y+dir[i][1]]!='X'){map[x + dir[i][0]][y + dir[i][1]]='X';dfs(x + dir[i][0], y + dir[i][1], cnt+1);map[x+dir[i][0]][y+dir[i][1]]='.'; //恢复回去}}return;}int main(){while(cin>>N>>M>>T, N){int wall=0;int si,sj;for(int i=1;i<=N;i++)for(int j=1;j<=M;j++){      cin>>map[i][j];if(map[i][j]=='S'){      si=i;sj=j;}else if(map[i][j]=='D'){di=i; dj=j;}else if(map[i][j]=='X')wall++;}if(T>=M*N-wall){      cout<<"NO"<<endl;continue;}map[si][sj]='X';escape=0;dfs(si,sj,0);if(escape==1)cout<<"YES"<<endl;elsecout<<"NO"<<endl;}}


原创粉丝点击