Welcome to Subscribe On Youtube

Formatted question description: https://leetcode.ca/all/778.html

778. Swim in Rising Water

Level

Hard

Description

On an N x N grid, each square grid[i][j] represents the elevation at that point (i,j).

Now 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 distance in zero time. Of course, you must stay within the boundaries of the grid during your swim.

You start at the top left square (0, 0). What is the least time until you can reach the bottom right square (N-1, N-1)?

Example 1:

Input: [[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: [[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:
 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

The final route is 0->1->2->3->4->5->16->15->14->13->12->11->10->9->8->7->6.
We need to wait until time 16 so that (0, 0) and (4, 4) are connected.

Note:

  1. 2 <= N <= 50.
  2. grid[i][j] is a permutation of [0, …, N*N - 1].

Solution

Use a priority queue to store the cells, where the cell with the minimum value in grid is polled first. Initially, offer (0, 0) to the priority queue. Also use a 2D array to store whether each cell is visited. Each time poll a cell from the priority queue and update the minimum time using the current cell’s value, if the current cell is at the bottom right corner, then break the loop. Otherwise, check its adjacent cells. If an adjacent cell has not been visited, then set the adjacent cell to visited and offer the adjacent cell to the priority queue. Finally, return the minimum time.

  • class Solution {
        public int swimInWater(int[][] grid) {
            int sideLength = grid.length;
            int totalCells = sideLength * sideLength;
            int minTime = Math.max(grid[0][0], grid[sideLength - 1][sideLength - 1]);
            boolean[][] visited = new boolean[sideLength][sideLength];
            visited[0][0] = true;
            PriorityQueue<int[]> priorityQueue = new PriorityQueue<int[]>(new Comparator<int[]>() {
                public int compare(int[] cell1, int[] cell2) {
                    return grid[cell1[0]][cell1[1]] - grid[cell2[0]][cell2[1]];
                }
            });
            priorityQueue.offer(new int[]{0, 0});
            int[][] directions = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} };
            while (!priorityQueue.isEmpty()) {
                int[] cell = priorityQueue.poll();
                minTime = Math.max(minTime, grid[cell[0]][cell[1]]);
                if (cell[0] == sideLength - 1 && cell[1] == sideLength - 1)
                    break;
                for (int[] direction : directions) {
                    int newRow = cell[0] + direction[0], newColumn = cell[1] + direction[1];
                    if (newRow >= 0 && newRow < sideLength && newColumn >= 0 && newColumn < sideLength && !visited[newRow][newColumn]) {
                        visited[newRow][newColumn] = true;
                        priorityQueue.offer(new int[]{newRow, newColumn});
                    }
                }
            }
            return minTime;
        }
    }
    
  • // OJ: https://leetcode.com/problems/swim-in-rising-water/
    // Time: O(N^2 * logN)
    // Space: O(N^2)
    class Solution {
        int N, dirs[4][2] = { {0,1},{0,-1},{1,0},{-1,0} };
        vector<vector<bool>> seen;
        bool dfs(vector<vector<int>> &G, int x, int y, int height) {
            if (G[x][y] > height) return false;
            if (x == N - 1 && y == N - 1) return true;
            seen[x][y] = true;
            for (auto &[dx, dy] : dirs) {
                int a = x + dx, b = y + dy;
                if (a < 0 || a >= N || b < 0 || b >= N || seen[a][b]) continue;
                if (dfs(G, a, b, height)) return true;
            }
            return false;
        }
        bool valid(vector<vector<int>>& G, int height) {
            seen.assign(N, vector<bool>(N, false));
            return dfs(G, 0, 0, height);
        }
    public:
        int swimInWater(vector<vector<int>>& G) {
            N = G.size();
            int L = 0, R = N * N - 1;
            while (L <= R) {
                int M = (L + R) / 2;
                if (valid(G, M)) R = M - 1;
                else L = M + 1;
            }
            return L;
        }
    };
    
  • class Solution:
        def swimInWater(self, grid: List[List[int]]) -> int:
            def find(x):
                if p[x] != x:
                    p[x] = find(p[x])
                return p[x]
    
            n = len(grid)
            p = list(range(n * n))
            hi = [0] * (n * n)
            for i, row in enumerate(grid):
                for j, h in enumerate(row):
                    hi[h] = i * n + j
            for t in range(n * n):
                i, j = hi[t] // n, hi[t] % n
                for a, b in [(0, -1), (0, 1), (1, 0), (-1, 0)]:
                    x, y = i + a, j + b
                    if 0 <= x < n and 0 <= y < n and grid[x][y] <= t:
                        p[find(x * n + y)] = find(hi[t])
                    if find(0) == find(n * n - 1):
                        return t
            return -1
    
    ############
    
    class Solution(object):
        def swimInWater(self, grid):
            """
            :type grid: List[List[int]]
            :rtype: int
            """
            n = len(grid)
            left, right = 0, n * n - 1
            while left <= right:
                mid = left + (right - left) / 2
                if self.dfs([[False] * n for _ in range(n)], grid, mid, n, 0, 0):
                    right = mid - 1
                else:
                    left = mid + 1
            return left
            
        def dfs(self, visited, grid, mid, n, i, j):
            visited[i][j] = True
            if i == n - 1 and j == n - 1:
                return True
            directions = [(0, 1), (0, -1), (-1, 0), (1, 0)]
            for dir in directions:
                x, y = i + dir[0], j + dir[1]
                if x < 0 or x >= n or y < 0 or y >= n or visited[x][y] or max(mid, grid[i][j]) != max(mid, grid[x][y]):
                    continue
                if self.dfs(visited, grid, mid, n, x, y):
                    return True
            return False
    
  • func swimInWater(grid [][]int) int {
    	n := len(grid)
    	p := make([]int, n*n)
    	for i := range p {
    		p[i] = i
    	}
    	hi := make([]int, n*n)
    	for i, row := range grid {
    		for j, h := range row {
    			hi[h] = i*n + j
    		}
    	}
    	var find func(x int) int
    	find = func(x int) int {
    		if p[x] != x {
    			p[x] = find(p[x])
    		}
    		return p[x]
    	}
    	dirs := []int{-1, 0, 1, 0, -1}
    	for t := 0; t < n*n; t++ {
    		i, j := hi[t]/n, hi[t]%n
    		for k := 0; k < 4; k++ {
    			x, y := i+dirs[k], j+dirs[k+1]
    			if x >= 0 && x < n && y >= 0 && y < n && grid[x][y] <= t {
    				p[find(x*n+y)] = find(hi[t])
    			}
    			if find(0) == find(n*n-1) {
    				return t
    			}
    		}
    	}
    	return -1
    }
    
  • function swimInWater(grid: number[][]): number {
        const m = grid.length,
            n = grid[0].length;
        let visited = Array.from({ length: m }, () => new Array(n).fill(false));
        let ans = 0;
        let stack = [[0, 0, grid[0][0]]];
        const dir = [
            [0, 1],
            [0, -1],
            [1, 0],
            [-1, 0],
        ];
    
        while (stack.length) {
            let [i, j] = stack.shift();
            ans = Math.max(grid[i][j], ans);
            if (i == m - 1 && j == n - 1) break;
            for (let [dx, dy] of dir) {
                let x = i + dx,
                    y = j + dy;
                if (x < m && x > -1 && y < n && y > -1 && !visited[x][y]) {
                    visited[x][y] = true;
                    stack.push([x, y, grid[x][y]]);
                }
            }
            stack.sort((a, b) => a[2] - b[2]);
        }
        return ans;
    }
    
    

All Problems

All Solutions