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

&nbsp;
Example 1:

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.


Example 2:

Input: grid = [[0,1,2,3,4],[24,23,22,21,5],[12,13,14,15,16],[11,17,18,19,20],[10,9,8,7,6]]
Output: 16
Explanation: The final route is shown.
We need to wait until time 16 so that (0, 0) and (4, 4) are connected.


&nbsp;
Constraints:


	n == grid.length
	n == grid[i].length
	1 &lt;= n &lt;= 50
	0 &lt;= grid[i][j] &lt;&nbsp;n2
	Each value grid[i][j] is unique.


class DSU(object):
    def __init__(self, N):
        self.par = list(range(N))
        self.rnk = [0] * N

    def find(self, x):
        if self.par[x] != x:
            self.par[x] = self.find(self.par[x])
        return self.par[x]

    def union(self, x, y):
        xr, yr = self.find(x), self.find(y)
        if xr == yr:
            return False
        elif self.rnk[xr] < self.rnk[yr]:
            self.par[xr] = yr
        elif self.rnk[xr] > self.rnk[yr]:
            self.par[yr] = xr
        else:
            self.par[yr] = xr
            self.rnk[xr] += 1
        return True

class Solution:
    def swimInWater(self, grid):
        d, N = {}, len(grid)
        for i,j in product(range(N), range(N)):
            d[grid[i][j]] = (i, j)
        
        dsu = DSU(N*N)
        grid = [[0] * N for _ in range(N)] 
        neib_list = [[0,1],[0,-1],[1,0],[-1,0]]
        
        for i in range(N*N):
            x, y = d[i]
            grid[x][y] = 1
            for dx, dy in neib_list:
                if N>x+dx>=0 and N>y+dy>=0 and grid[x+dx][y+dy] == 1:
                    dsu.union((x+dx)*N + y + dy, x*N + y)
                    
            if dsu.find(0) == dsu.find(N*N-1): return i
class Solution {
    public int swimInWater(int[][] grid) {
        int len = grid.length;
        Map<Integer, int[]> reverseMap = new HashMap<>();
        for (int i = 0; i < len; i++) {
            for (int j = 0; j < len; j++) {
                reverseMap.put(grid[i][j], new int[] { i, j });
            }
        }
        
        int left = grid[0][0]; // answer cannot be less than value of starting position
        int right = len * len - 1;
        
        int ans = right;
        
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (canSwim(grid, reverseMap, mid, len)) {
                ans = mid;
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        
        return ans;
    }
    
    boolean canSwim(int[][] grid, Map<Integer, int[]> reverseIndex, int ans, int len) {
        int[] x_diff = { 1, -1, 0, 0 };
        int[] y_diff = { 0, 0, 1, -1 };
        
        // BFS
        Queue<int[]> container = new LinkedList<>();
        container.add(new int[] { 0, 0 });
        
        boolean[][] visited = new boolean[grid.length][grid[0].length];
        visited[0][0] = true;
            
        while (!container.isEmpty()) {
            int[] curr = container.poll();
            int currVal = grid[curr[0]][curr[1]];
            for (int i = 0; i < 4; i++) {
                int newX = curr[0] + x_diff[i];
                int newY = curr[1] + y_diff[i];
                if (isValidCell(grid, newX, newY, ans) && !visited[newX][newY]) {
                    if (newX == grid.length-1 && newY == grid[0].length-1) {
                        return true;
                    }
                    visited[newX][newY] = true;
                    container.add(new int[] { newX, newY });
                }
            }   
        }
        
        return false;
    }
    
    boolean isValidCell(int[][] grid, int x, int y, int ans) {
	    // check boundary and if grid elevation is greater than evaluated answer
        return !(x < 0 || x >= grid.length || y < 0 || y >= grid[0].length || grid[x][y] > ans);
    }
}
class Solution {
public:
    int dir[4][2]={{0,1},{1,0},{-1,0},{0,-1}};
    bool valid(int x,int y,int n)
    {
        return ((x>=0&&x<n)&&(y>=0&&y<n));
    }
    int swimInWater(vector<vector<int>>& grid) {
        int n=grid.size();
        int time[n][n];
        bool vis[n][n];
        for(int i=0;i<n;++i)
        {
            for(int j=0;j<n;++j)
            {
                time[i][j]=1e9;
                vis[i][j]=false;
            }
        }
        time[0][0]=grid[0][0];
        priority_queue<tuple<int,int,int>> q;
        q.push({-time[0][0],0,0});
        while(!q.empty())
        {
            tuple<int,int,int> node=q.top();
            q.pop();
            int x=get<1>(node),y=get<2>(node);
            if(vis[x][y])continue;
            vis[x][y]=true;
            for(int i=0;i<4;++i)
            {
                int xc=x+dir[i][0],yc=y+dir[i][1];
                if(!valid(xc,yc,n))continue;
                if(time[x][y]<grid[xc][yc])
                {
                    time[xc][yc]=grid[xc][yc];
                    q.push({-time[xc][yc],xc,yc});
                }
                else
                {
                    if(time[xc][yc]>time[x][y])
                    {
                        time[xc][yc]=time[x][y];
                        q.push({-time[xc][yc],xc,yc});
                    }
                }
            }
        }
        return time[n-1][n-1];
    }
};
// Time: O(N*N+N*NLOG(N*N))
// Space: O(N*N)
const moves = [[1,0],[0,1],[-1,0],[0,-1]]

var swimInWater = function(grid) {
    let pq = new MinPriorityQueue(),
        N = grid.length - 1, ans = grid[0][0], i = 0, j = 0
    while (i < N || j < N) {
        for (let [a,b] of moves) {
            let ia = i + a, jb = j + b
            if (ia < 0 || ia > N || jb < 0 || jb > N || grid[ia][jb] > 2500) continue
            pq.enqueue((grid[ia][jb] << 12) + (ia << 6) + jb)
            grid[ia][jb] = 3000
        }
        let next = pq.dequeue().element
        ans = Math.max(ans, next >> 12)
        i = (next >> 6) & ((1 << 6) - 1)
        j = next & ((1 << 6) - 1)
    }
    return ans
};
Swim in Rising Water