Advertisement
Singasking

Untitled

Jun 27th, 2023
592
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.58 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     bool dfs(vector<vector<int>>& heights, int r, int c, int currEffort, int& minEffort, vector<vector<int>>& visited) {
  4.         int N = heights.size();
  5.         int M = heights[0].size();
  6.         visited[r][c] = 1;
  7.  
  8.         // Check if reached the destination
  9.         if (r == N - 1 && c == M - 1) {
  10.             minEffort = min(minEffort, currEffort);
  11.             return true;
  12.         }
  13.  
  14.         vector<pair<int, int>> dirs = {{r+1, c}, {r-1, c}, {r, c-1}, {r, c+1}};
  15.         for (auto dir : dirs) {
  16.             int rn = dir.first;
  17.             int cn = dir.second;
  18.             // Check validity
  19.             if (rn >= 0 && rn < N && cn >= 0 && cn < M && visited[rn][cn] == 0) {
  20.                 int nextEffort = abs(heights[rn][cn] - heights[r][c]);
  21.                 int newEffort = max(currEffort, nextEffort);
  22.  
  23.                 // Prune if the new effort is already higher than the minimum effort found so far
  24.                 if (newEffort >= minEffort)
  25.                     continue;
  26.  
  27.                 if (dfs(heights, rn, cn, newEffort, minEffort, visited)) {
  28.                     // If the path is found, return immediately
  29.                     return true;
  30.                 }
  31.             }
  32.         }
  33.  
  34.         return false;
  35.     }
  36.  
  37.     int minimumEffortPath(vector<vector<int>>& heights) {
  38.         int rows = heights.size();
  39.         int cols = heights[0].size();
  40.         vector<vector<int>> visited(rows, vector<int>(cols, 0));
  41.         int minEffort = INT_MAX;
  42.         dfs(heights, 0, 0, 0, minEffort, visited);
  43.         return minEffort;
  44.     }
  45. };
  46.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement