Advertisement
matheus_monteiro

Pulo do Gato (P1)

Sep 18th, 2021
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.86 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. #define ii pair<int, int>
  4. #define fi first
  5. #define se second
  6.  
  7. int n, m;
  8. int M[600][600];
  9. int dist[600][600];
  10.  
  11. bool check(int x, int y) {
  12.     return x >= 0 and x < n and y >= 0 and y < m;
  13. }
  14.  
  15. int bfs() {
  16.     queue<ii> q;
  17.     q.push({0, 0});
  18.     memset(dist, -1, sizeof(dist));
  19.     dist[0][0] = 0;
  20.    
  21.     while(!q.empty()) {
  22.         ii a = q.front();
  23.         q.pop();
  24.        
  25.         for(int i = -2; i <= 2; i++)
  26.             for(int j = -2; j <= 2; j++) {
  27.                 if(!i and !j) continue;
  28.                 int x = i + a.fi, y = j + a.se;
  29.                 if(check(x, y) and dist[x][y] == -1 and M[x][y]) {
  30.                     dist[x][y] = dist[a.fi][a.se] + 1;
  31.                     q.push({x, y});
  32.                 }
  33.             }
  34.        
  35.        
  36.     }
  37.     return dist[n - 1][m - 1];
  38. }
  39.  
  40. int32_t main()
  41. {
  42.     cin >> n >> m;
  43.     for(int i = 0; i < n; i++)
  44.         for(int j = 0; j < m; j++)
  45.             cin >> M[i][j];
  46.            
  47.     cout << bfs() << '\n';
  48.    
  49.     return 0;
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement