View on NeetCode
View on LeetCode

Problem

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

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.

Constraints:

  • n == grid.length
  • n == grid[i].length
  • 1 <= n <= 50
  • 0 <= grid[i][j] < n²
  • Each value grid[i][j] is unique.

Solution

Approach 1: Modified Dijkstra’s Algorithm

The key insight is to find the path where the maximum elevation along the path is minimized. This is a variant of shortest path with min-max cost.

Implementation

import heapq

class Solution:
    def swimInWater(self, grid: List[List[int]]) -> int:
        n = len(grid)
        visited = set()
        min_heap = [(grid[0][0], 0, 0)]  # (max_elevation, row, col)

        directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]

        while min_heap:
            max_elev, r, c = heapq.heappop(min_heap)

            if (r, c) in visited:
                continue

            visited.add((r, c))

            # Reached destination
            if r == n - 1 and c == n - 1:
                return max_elev

            # Explore neighbors
            for dr, dc in directions:
                nr, nc = r + dr, c + dc
                if (0 <= nr < n and 0 <= nc < n and
                    (nr, nc) not in visited):
                    # Max elevation is the max of current path and next cell
                    new_max = max(max_elev, grid[nr][nc])
                    heapq.heappush(min_heap, (new_max, nr, nc))

        return -1

Approach 2: Binary Search + BFS

from collections import deque

class Solution:
    def swimInWater(self, grid: List[List[int]]) -> int:
        n = len(grid)

        def can_reach(time):
            """Check if we can reach destination with given time"""
            if grid[0][0] > time:
                return False

            visited = set([(0, 0)])
            queue = deque([(0, 0)])
            directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]

            while queue:
                r, c = queue.popleft()

                if r == n - 1 and c == n - 1:
                    return True

                for dr, dc in directions:
                    nr, nc = r + dr, c + dc
                    if (0 <= nr < n and 0 <= nc < n and
                        (nr, nc) not in visited and grid[nr][nc] <= time):
                        visited.add((nr, nc))
                        queue.append((nr, nc))

            return False

        # Binary search on time
        left, right = 0, n * n - 1

        while left < right:
            mid = (left + right) // 2
            if can_reach(mid):
                right = mid
            else:
                left = mid + 1

        return left

Complexity Analysis

Dijkstra Approach:

  • Time Complexity: O(N² log N), where N is grid dimension. We process each cell once with heap operations.
  • Space Complexity: O(N²) for the heap and visited set.

Binary Search + BFS:

  • Time Complexity: O(N² log(N²)) = O(N² log N). Binary search with O(N²) BFS per iteration.
  • Space Complexity: O(N²) for BFS visited set.

Key Insights

  1. Min-Max Path: We need the path where the maximum elevation is minimized - not the sum, but the max along the path.

  2. Modified Dijkstra: Instead of tracking sum of costs, we track the maximum elevation seen so far on each path.

  3. Greedy Choice: Always process the cell with minimum “maximum elevation so far”, which gives us the optimal path.

  4. Binary Search Alternative: Since elevations are bounded (0 to N²-1), we can binary search on the time and check reachability.

  5. Monotonic Property: If we can reach destination at time t, we can also reach it at time t+1, making binary search applicable.

  6. Water Level: Time t means we can only travel on cells with elevation ≤ t.