Swim in Rising Water LeetCode Solution

Difficulty Level Hard
Frequently asked in Amazon Apple DoorDash Facebook Google MicrosoftViews 1280

Problem Statement:

Swim in Rising Water LeetCode Solution : You are given an n x n integer matrix grid where each value grid[i][j] represents the elevation at that point (i, j).

The rain starts to fall. At time t, the depth of the water everywhere is t. You can swim from a square to another 4-directionally adjacent square if and only if the elevation of both squares individually is at most t. You can swim infinite distances in zero time. Of course, you must stay within the boundaries of the grid during your swim.

Return the least time until you can reach the bottom right square (n - 1, n - 1) if you start at the top left square (0, 0).

Examples:

Input:

 grid = [[0,2],[1,3]]

Output:

 3
Explanation:
At time 0, you are in grid location (0, 0).
You cannot go anywhere else because 4-directionally adjacent neighbors have a higher elevation than t = 0.
You cannot reach point (1, 1) until time 3.
When the depth of water is 3, we can swim anywhere inside the grid.

Approach:

Idea:

We will be solving the problem using Binary Search and BFS.  The idea is to use a binary search for the minimum time T for which you can reach the end. For every possible value of T, we will check if it’s possible to reach the last cell or not and will try to minimize this value.

Swim in Rising Water LeetCode Solution

Code for Swim in Rising Water LeetCode Solution:

Swim in Rising Water C++ Solution:

class Solution {
public:
    int n;
    bool search(vector<vector<int>>& grid, int depth){
        queue<pair<int,int>> q;
        q.push({0,0});
        
        vector<vector<int>> dirs = {{0,1},{1,0},{0,-1},{-1,0}};
        set<pair<int,int>> vis;
        while(!q.empty()){
            pair<int,int> top = q.front();
            q.pop();
            for(auto it:dirs){
                int x = top.first + it[0];
                int y = top.second + it[1];
                if(x==n-1 and y==n-1 and grid[x][y]<=depth)
                    return true;
                if(x>=0 and y>=0 and x<n and y<n and grid[x][y]<=depth and !vis.count({x,y})){
                    q.push({x,y});
                    vis.insert({x,y});
                }
            }
        }
        return false;
    }
    
    int swimInWater(vector<vector<int>>& grid) {
        n = grid.size();
        if(n==1)
            return 0;
        int l = grid[0][0];
        int r = 2500;
        int ans = INT_MAX;
        while(l<=r){
            int m = (l+r)/2;
            if(search(grid,m)){
                ans = min(ans,m);
                r = m-1;
            }
            else{
                l = m+1;
            }
        }
        return ans;
    }
};

Complexity Analysis of Swim in Rising Water LeetCode Solution:

Translate »