fork download
  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include <iostream>
  3. #include <string>
  4. #include <string.h>
  5. #include <vector>
  6. #include <algorithm>
  7. #include <cmath>
  8. #include <queue>
  9. #include <stack>
  10. #include <map>
  11. #include <set>
  12. using namespace std;
  13.  
  14. void dfs(int y, int x, int cnt);
  15.  
  16. int x_move[4] = {0, 0, 1, -1};
  17. int y_move[4] = {1, -1, 0, 0};
  18. int N, M;
  19. int ans = 100001;
  20. int **maze;
  21. bool **visited;
  22.  
  23. int main()
  24. {
  25. ios::sync_with_stdio(false);
  26. cin.tie(NULL);
  27.  
  28. cin >> N >> M;
  29.  
  30. maze = new int *[N];
  31. visited = new bool *[N];
  32.  
  33. for (int i = 0; i < N; i++)
  34. {
  35. maze[i] = new int[M];
  36.  
  37. visited[i] = new bool[M]{false};
  38. }
  39.  
  40. for (int i = 0; i < N; i++)
  41. {
  42. for (int j = 0; j < M; j++)
  43. {
  44. scanf("%1d", &maze[i][j]);
  45. }
  46. }
  47.  
  48. visited[0][0] = true;
  49.  
  50. dfs(0, 0, 1);
  51.  
  52. cout << ans;
  53.  
  54. for (int i = 0; i < N; i++)
  55. {
  56. delete[] maze[i];
  57. delete[] visited[i];
  58. }
  59.  
  60. delete[] maze;
  61. delete[] visited;
  62.  
  63. return 0;
  64. }
  65.  
  66. void dfs(int y, int x, int cnt)
  67. {
  68. if (x == M - 1 && y == N - 1)
  69. {
  70. ans = min(ans, cnt);
  71.  
  72. return;
  73. }
  74.  
  75. for (int i = 0; i < 4; i++)
  76. {
  77. int next_x = x + x_move[i];
  78. int next_y = y + y_move[i];
  79.  
  80. if (0 <= next_x && next_x < M && 0 <= next_y && next_y < N)
  81. {
  82. if (!visited[next_y][next_x] && maze[next_y][next_x] == 1)
  83. {
  84. visited[next_y][next_x] = true;
  85.  
  86. dfs(next_y, next_x, cnt + 1);
  87.  
  88. visited[next_y][next_x] = false;
  89. }
  90. }
  91. }
  92. }
Success #stdin #stdout 0.01s 5512KB
stdin
8 8
10111111
11100001
10000001
10111101
10100101
10100101
10100101
11100111
stdout
100001