Advertisement
Guest User

Untitled

a guest
Mar 30th, 2017
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4. char maze[20][20]; // store the actual maze
  5. bool visit[20][20]; // to avoid repeating visit
  6. int N = 0; // to store how many dead-ends
  7.  
  8. struct point
  9. {
  10. int x, y;
  11. point(int a, int b)
  12. {
  13. x = a;
  14. y = b;
  15. }
  16. };
  17.  
  18. // Check if the target point is feasible to explore
  19. int pushIfValid(point target, int H, int W, stack<point> &s)
  20. {
  21. if (target.x >= 0 && target.x < W && target.y < H && target.y >= 0)
  22. {
  23. if (maze[target.y][target.x] == '#')
  24. {
  25. return 1;
  26. }
  27. else
  28. {
  29. s.push(target);
  30. }
  31. }
  32. return 0;
  33. }
  34.  
  35. // Explore the maze with depth first search traversal (managing own stack)
  36. void dfs_explore(point start, int H, int W)
  37. {
  38. stack<point> s;
  39. s.push(start);
  40.  
  41. while (!s.empty())
  42. {
  43. point current = s.top();
  44. s.pop();
  45. if(maze[current.y][current.x] != '#' && !visit[current.y][current.x])
  46. {
  47. visit[current.y][current.x] = true;
  48. int temp = 0;
  49. temp += pushIfValid(point(current.x + 1, current.y), H, W, s);
  50. temp += pushIfValid(point(current.x - 1, current.y), H, W, s);
  51. temp += pushIfValid(point(current.x, current.y + 1), H, W, s);
  52. temp += pushIfValid(point(current.x, current.y - 1), H, W, s);
  53.  
  54. // if any 3 direction is dead-end, we increase count of dead ends
  55. if (temp == 3)
  56. {
  57. ++N;
  58. }
  59. }
  60. }
  61. }
  62.  
  63.  
  64. int main()
  65. {
  66. int C;
  67. cin >> C;
  68. for (int i = 1; i <= C; ++i)
  69. {
  70. int H, W;
  71. N = 0;
  72. cin >> H >> W;
  73.  
  74. // get the labyrinth
  75. for(int y = 0; y < H; ++y)
  76. {
  77. for (int x = 0; x < W; ++x)
  78. {
  79. cin >> maze[y][x];
  80. }
  81. }
  82.  
  83. // reset the maze state (unvisited)
  84. for (int i = 0; i < 20; ++i)
  85. for (int j = 0; j < 20; ++j)
  86. visit[i][j] = false;
  87.  
  88. dfs_explore(point(1, 0), H, W); // explore from the starting point
  89. cout << "Case #" << i << ": " << N << endl;
  90.  
  91. }
  92. return 0;
  93. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement