Advertisement
nikunjsoni

1631

May 14th, 2021
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.10 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int minimumEffortPath(vector<vector<int>> &heights){
  4.         int left = 0;
  5.         int right = 1000000;
  6.         int result = right;
  7.         while (left <= right) {
  8.             int mid = (left + right)/2;
  9.             if(canReachDestinaton(heights, mid)){
  10.                 result = min(result, mid);
  11.                 right = mid - 1;
  12.             }
  13.             else{
  14.                 left = mid + 1;
  15.             }
  16.         }
  17.         return result;
  18.     }
  19.  
  20.     int directions[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
  21.  
  22.     // use bfs to check if we can reach destination with max absolute difference
  23.     // k
  24.     bool canReachDestinaton(vector<vector<int>> &heights, int mid){
  25.         int row = heights.size();
  26.         int col = heights[0].size();
  27.         queue<Cell> queue;
  28.         vector<vector<bool>> visited(row, vector<bool>(col, false));
  29.         queue.push(Cell(0, 0));
  30.         visited[0][0] = true;
  31.         while(!queue.empty()){
  32.             Cell curr = queue.front();
  33.             queue.pop();
  34.             if(curr.x == row - 1 && curr.y == col - 1){
  35.                 return true;
  36.             }
  37.             for(auto direction : directions){
  38.                 int adjacentX = curr.x + direction[0];
  39.                 int adjacentY = curr.y + direction[1];
  40.                 if (isValidCell(adjacentX, adjacentY, row, col) &&
  41.                     !visited[adjacentX][adjacentY]){
  42.                     int currentDifference = abs(heights[adjacentX][adjacentY] -
  43.                                                 heights[curr.x][curr.y]);
  44.                     if(currentDifference <= mid){
  45.                         visited[adjacentX][adjacentY] = true;
  46.                         queue.push(Cell(adjacentX, adjacentY));
  47.                     }
  48.                 }
  49.             }
  50.         }
  51.         return false;
  52.     }
  53.  
  54.     bool isValidCell(int x, int y, int row, int col){
  55.         return x >= 0 && x <= row - 1 && y >= 0 && y <= col - 1;
  56.     }
  57.  
  58.     class Cell{
  59.     public:
  60.         int x, y;
  61.         Cell(int x, int y){
  62.             this->x = x;
  63.             this->y = y;
  64.         }
  65.     };
  66. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement