Swim in Rising Water LeetCode Solution

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

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).



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


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.



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 {
    int n;
    bool search(vector<vector<int>>& grid, int depth){
        queue<pair<int,int>> q;
        vector<vector<int>> dirs = {{0,1},{1,0},{0,-1},{-1,0}};
        set<pair<int,int>> vis;
            pair<int,int> top = q.front();
            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})){
        return false;
    int swimInWater(vector<vector<int>>& grid) {
        n = grid.size();
            return 0;
        int l = grid[0][0];
        int r = 2500;
        int ans = INT_MAX;
            int m = (l+r)/2;
                ans = min(ans,m);
                r = m-1;
                l = m+1;
        return ans;

Complexity Analysis of Swim in Rising Water LeetCode Solution:

Translate »