fork download
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. #define int long long
  6. #define ld long double
  7. #define eb emplace_back
  8. #define pb push_back
  9. #define fi first
  10. #define se second
  11. #define nn '\n'
  12. #define pi pair<int, int>
  13. #define unmp unordered_map
  14. #define uns unordered_set
  15. #define lb lower_bound
  16. #define ub upper_bound
  17. #define pq priority_queue
  18. #define TASK " "
  19.  
  20. #define FOR(i, a, n) for(int i = (a) ; i <= (n) ; i++ )
  21. #define FORD(i, a, n) for(int i = (a); i >= (n); i--)
  22. #define FORX(i, x) for(int (i) : (x))
  23. #define ms(a, x) memset((a), (x), sizeof((a)))
  24. #define all(a) (a).begin(), (a).end()
  25. #define All(a, n) (a) + 1, (a) + 1 + n
  26.  
  27.  
  28. const int INF = 1e18;
  29. const int mod = 1e9+7;
  30. const int N = 1e2 + 5;
  31. int MOD = 998244353;
  32. int bit[200000];
  33. int n, m;
  34. int d[N][N];
  35. bool vis[N][N];
  36. int a[N][N];
  37. int moveX[] = {0, 0, 1, -1};
  38. int moveY[] = {1, -1, 0, 0};
  39. int st, sy;
  40. bool ok;
  41.  
  42. void nhap(){
  43. cin >> m >> n;
  44. cin >> st >> sy;
  45. FOR(i, 1, m){
  46. FOR(j, 1, n){
  47. cin >> a[i][j];
  48. }
  49. }
  50. }
  51. void bfs(int sx, int sy){
  52. d[sx][sy] = 0;
  53. queue<pi> q;
  54. vis[sx][sy] = 1;
  55. q.push({sx, sy});
  56. while(!q.empty()){
  57. int x = q.front().fi;
  58. int y = q.front().se;
  59. q.pop();
  60. if(x == 1 || x == n || y == 1 || y == m){
  61. ok = true;
  62. cout<< d[x][y] << nn;
  63. return;
  64. }
  65. FOR(i, 0, 3){
  66. int u = x + moveX[i];
  67. int v = y + moveY[i];
  68.  
  69.  
  70. if(u < 1 || u > n || v < 1 || v > m || a[u][v] == 1){
  71. continue;
  72. }
  73. if(!vis[u][v]){
  74. d[u][v] = d[x][y] + 1;
  75. vis[u][v] = 1;
  76. q.push({u, v});
  77. }
  78. }
  79. }
  80.  
  81. }
  82. signed main() {
  83. //freopen("CSBN.INP", "r", stdin);
  84. //freopen("CSBN.OUT", "w", stdout);
  85. ios_base::sync_with_stdio(0);
  86. cin.tie(0);
  87. cout.tie(0);
  88. nhap();
  89. bfs(st, sy);
  90. return 0;
  91.  
  92. }
  93.  
Success #stdin #stdout 0s 544KB
stdin
5 6
3 2
1 1 1 0 1 0
1 0 1 0 1 0
1 0 0 0 1 0
0 0 1 0 1 0
1 1 0 0 0 0
stdout
2