hdu 1010 dfs奇偶剪枝

  1. #include <iostream>
  2. #include <cmath>
  3. using namespace std;
  4. int N, M, T, sx, sy, ex, ey; //sx,sy起点坐标 ex,ey终点坐标
  5. char map[6][6];
  6. const int dir[4][2] = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } };
  7. bool solved = false, arrd[6][6];
  8. int Distance ( int x, int y )
  9. {
  10. return abs ( (double)x - ex ) + abs ( (double)y - ey ); // 当前点(x,y)到终点(ex,ey)的最短距离
  11. }
  12. void DFS ( int x, int y, int step )
  13. {
  14. if ( solved ) return;
  15. if ( map[x][y] == 'D' && step == T ) {
  16. solved = true;
  17. return;
  18. }
  19. if ( step >= T ) return; // 当前时间即步数(step) >= T 而且还没有找到D点
  20. int dis = T - step - Distance ( x, y );
  21. if ( dis < 0 || dis % 2 ) return; // 剩余步数小于最短距离或者满足奇偶剪枝条件
  22. for ( int i = 0; i < 4; i ++ ) {
  23. int tx = x + dir[i][0];
  24. int ty = y + dir[i][1];
  25. int tstep = step + 1;
  26. if ( tx >= 0 && tx < N && ty >= 0 && ty < M && map[tx][ty] != 'X' && !arrd[tx][ty]) {
  27. arrd[tx][ty] = true;
  28. DFS ( tx, ty, tstep );
  29. arrd[tx][ty] = false;
  30. }
  31. }
  32. }
  33. int main ( int argc, char *argv[] )
  34. {
  35. while ( cin >> N >> M >> T, N+M+T )
  36. {
  37. solved = false;
  38. int xnum = 0; // 记录'X'的数量
  39. for ( int i = 0; i < N; i += 1 )
  40. {
  41. cin.get();
  42. for ( int j = 0; j < M; j += 1 )
  43. {
  44. cin >> map[i][j];
  45. arrd[i][j] = false;
  46. if ( map[i][j] == 'S' )
  47. {
  48. sx = i;
  49. sy = j;
  50. arrd[i][j] = true;
  51. }
  52. else if ( map[i][j] == 'D' )
  53. {
  54. ex = i;
  55. ey = j;
  56. }
  57. else if ( map[i][j] == 'X' )
  58. xnum++;
  59. }
  60. }
  61. if ( N * M - xnum > T ) { // 可通行的点必须大于要求的步数,路径剪枝。
  62. DFS ( sx, sy, 0 );
  63. }
  64. if ( solved )
  65. cout << "YES" << endl;
  66. else
  67. cout << "NO" << endl;
  68. }
  69. return 0;
  70. }





附件列表

     

    posted @ 2015-01-29 15:36  sober_reflection  阅读(133)  评论(0编辑  收藏  举报