nikunjsoni

505

May 3rd, 2021
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.10 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int shortestDistance(vector<vector<int>>& maze, vector<int>& start, vector<int>& destination) {
  4.     int m = maze.size();
  5.     int n = maze[0].size();
  6.     int minDist = INT_MAX;
  7.  
  8.     vector<vector<int>> dists(m, vector<int>(n, INT_MAX));
  9.     queue<pair<int, int>> q;
  10.  
  11.     vector<pair<int, int>> incr = {{1,0},{0,-1},{0,1},{-1,0}};
  12.  
  13.     q.push({start[0], start[1]});
  14.     dists[start[0]][start[1]] = 0;
  15.  
  16.     while (!q.empty()){
  17.         auto curr = q.front();
  18.         q.pop();
  19.         int x = curr.first;
  20.         int y = curr.second;
  21.         int dist = dists[x][y];
  22.  
  23.         for(int k = 0; k < 4; ++k){
  24.             int i = x;
  25.             int j = y;
  26.             int step = 0;
  27.             int d_i = incr[k].first;
  28.             int d_j = incr[k].second;
  29.             int tempMin = INT_MAX;
  30.  
  31.             while(i + d_i < m && i + d_i >= 0 && j + d_j >= 0 && j + d_j <n && maze[i + d_i][j + d_j] == 0){
  32.                 ++step;
  33.                 i += incr[k].first;
  34.                 j += incr[k].second;
  35.             }
  36.             if(dists[i][j] > dist + step){
  37.                 dists[i][j] = dist + step;
  38.                 q.push({i,j});
  39.             }
  40.         }
  41.     }
  42.  
  43.     return (dists[destination[0]][destination[1]] == INT_MAX) ? -1 : dists[destination[0]][destination[1]];        
  44.     }
  45. };
Advertisement
Add Comment
Please, Sign In to add comment