HDOJ 1010 Tempter of the Bone
题意:一个N * M 的迷宫, 起点为S, 终点为D , 障碍为X, 问你是否恰好花费时间T 的时候到达终点D。
思路:DFS ,纯粹的搜索会直接超时, 所以需要通过剪枝, 也是在网上看到别人说奇偶剪枝,加进去直接AC了。
6923405 | 2012-10-15 15:09:01 | Accepted | 1010 | 640MS | 256K | 1465 B | C++ | 罗维 |
View Code
1 #include <iostream> 2 #include <string> 3 #include <vector> 4 #include <math.h> 5 using namespace std; 6 7 struct point 8 { 9 int x, y; 10 }; 11 int n, m, t; 12 point spt, dpt; 13 string maze[10]; 14 //vector<vecot<int> >used; 15 bool escape; 16 17 void dfs(point pt, int t) 18 { 19 int tmp = t - abs(pt.x-dpt.x) - abs(pt.y - dpt.y); 20 if(pt.x == dpt.x && pt.y == dpt.y && t == 0) 21 { 22 escape = true; 23 return ; 24 } 25 //剪枝 26 if (escape || tmp < 0 || tmp&1 ) //tmp&1 如果是奇数则为1 否则为0 27 return; 28 maze[pt.x][pt.y] = 'X'; 29 if(pt.x + 1 <n && maze[pt.x + 1][pt.y] != 'X') 30 { 31 pt.x += 1; 32 dfs(pt, t-1); 33 pt.x -= 1; 34 if(escape) return; 35 } 36 if(pt.x - 1 >=0 && maze[pt.x - 1][pt.y] != 'X') 37 { 38 pt.x -= 1; 39 dfs(pt, t-1); 40 pt.x += 1; 41 if(escape) return; 42 } 43 if(pt.y + 1 < m && maze[pt.x][pt.y + 1] != 'X') 44 { 45 pt.y += 1; 46 dfs(pt, t-1); 47 pt.y -= 1; 48 if(escape) return; 49 } 50 if(pt.y - 1 >= 0 && maze[pt.x][pt.y - 1] != 'X') 51 { 52 pt.y -= 1; 53 dfs(pt, t-1); 54 pt.y += 1; 55 if(escape) return; 56 } 57 maze[pt.x][pt.y] = '.'; 58 } 59 60 int main() 61 { 62 int i, j; 63 while(cin>>n>>m>>t && n+m+t != 0) 64 { 65 for (i=0; i<n; i++) 66 { 67 cin>>maze[i]; 68 for (j=0; j<m; j++) 69 { 70 if(maze[i][j] == 'S') 71 { 72 spt.x = i; 73 spt.y = j; 74 } 75 else if(maze[i][j] == 'D') 76 { 77 dpt.x = i; 78 dpt.y = j; 79 } 80 } 81 } 82 83 escape = false; 84 dfs(spt, t); 85 if(escape) 86 cout<<"YES"<<endl; 87 else 88 cout<<"NO"<<endl; 89 } 90 return 0; 91 }