Naxocist

NumberMaze

Apr 10th, 2022 (edited)
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.05 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. #define INF 1e9
  4.  
  5. const int N = 1010;
  6. int table[N][N], dist[N][N];
  7.  
  8. using pii = pair<int, int>;
  9.  
  10. int main(){
  11.     int n, m; scanf("%d %d", &n, &m);
  12.  
  13.     for(int i=1; i<=n; ++i){
  14.         for(int j=1 ; j<=m; ++j){
  15.             scanf("%d", &table[i][j]);
  16.             dist[i][j] = INF;
  17.         }
  18.     }
  19.  
  20.     priority_queue<pii, vector<pii>, greater<pii> > pq;
  21.  
  22.     int tx[] = {-1, 1, 0, 0}, ty[] = {0, 0, -1, 1};
  23.  
  24.     pq.push({1, 1});
  25.     dist[1][1] = table[1][1];
  26.     while(!pq.empty()){ // dijkstra's algorithm on 2d array
  27.         int  x = pq.top().first, y = pq.top().second;
  28.         pq.pop();
  29.  
  30.         for(int i=0; i<4; ++i){
  31.             int h = x + tx[i], k = y + ty[i];
  32.             if(h < 1 || k < 1 || h > n || k > m) continue;
  33.             int w = table[h][k];
  34.  
  35.             if(dist[x][y] + w < dist[h][k]){
  36.                 dist[h][k] = dist[x][y] + w;
  37.  
  38.                 pq.push({h, k});
  39.             }
  40.         }
  41.     }
  42.  
  43.  
  44.     printf("%d", dist[n][m]); // shortest path
  45.     return 0;
  46. }
  47.  
Add Comment
Please, Sign In to add comment