Press enter to see results or esc to cancel.

Swim In Rising Water Leetcode Problem 778 [Python Solution]

In this tutorial post, we’ll be solving the Swim In Rising Water LeetCode problem, falling under the category of advanced graphs.

We’ll explore the problem statement, constraints, and ultimately provide an efficient Python solution to tackle it.

If you’d like to refer to the original problem on LeetCode, you can find it here.

Problem Overview

You are given an n x n integer matrix grid where each value grid[i][j] represents the elevation at the point (i, j).

Imagine that it starts raining, and at time t, the depth of the water everywhere on the grid is t.

You can swim from one square to another if and only if the elevation of both squares is at most t.

The catch is that you can swim an infinite distance in zero time.

However, you must stay within the boundaries of the grid.

The task at hand is to find the least time until you can reach the bottom-right square (n - 1, n - 1) starting from 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 the adjacent neighbors have higher elevations than t = 0. You cannot reach point (1, 1) until time 3. When the depth of water is 3, you 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.

You 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^2 (Each value in grid is unique.)

Understanding Constraints

Before delving into the solution, let’s grasp the constraints of this problem.

  1. The grid is square (n x n).
  2. The elevation values in the grid are non-negative and unique.
  3. The matrix can have a size of up to 50×50.
  4. The values in the grid can range from 0 to n^2.

Swim In Rising Water LeetCode Problem Solution

Now, let’s explore the efficient Python solution to this problem.

We’ll be using a modified version of Dijkstra’s algorithm to solve this problem in a time-efficient manner.

def swimInWater(self, grid: List[List[int]]) -&gt; int:
    N = len(grid)
    visit = set()
    minH = [[grid[0][0], 0, 0]]  # (time/max-height, r, c)
    directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]

    visit.add((0, 0))
    while minH:
        t, r, c = heapq.heappop(minH)
        if r == N - 1 and c == N - 1:
            return t
        for dr, dc in directions:
            neiR, neiC = r + dr, c + dc
            if (
                neiR &lt; 0
                or neiC &lt; 0
                or neiR == N
                or neiC == N
                or (neiR, neiC) in visit
            ):
                continue
            visit.add((neiR, neiC))
            heapq.heappush(minH, [max(t, grid[neiR][neiC]), neiR, neiC])

This solution leverages a modified Dijkstra’s algorithm to efficiently find the minimum time to reach the bottom-right square.

We use a minimum heap (minH) to manage the frontier of the positions we explore.

The elements in the heap contain three components: time (max height), row, and column.

We initialize minH with the top-left corner’s height (the starting point), and we add this point to the visit set to keep track of visited positions.

Then, we proceed with a loop until minH is not empty.

Within the loop, we pop the element with the minimum time from the heap.

If this element corresponds to the bottom-right square, we return the time (max height) it took to reach that point.

If it’s not the destination, we explore its four neighboring positions.

If a neighboring position is out of bounds or has been visited, we skip it.

Otherwise, we add it to the heap, updating the time (max height) to be the maximum of the current time and the elevation at the new position.

This way, we ensure we’re taking the maximum height along the path.

This process continues until we find the minimum time to reach the destination, and that’s what we return as the answer.

Time and Space Complexity

  • Time Complexity: O(n^2 * log(n))
  • Space Complexity: O(n^2)

The time complexity of this solution is efficient, thanks to the use of the minimum heap.

We visit each position at most once, and each insertion and extraction operation on the heap takes O(log(n)) time.

The space complexity is O(n^2) due to the visit set and the minH heap.

Reasoning Behind Our Approach

In this problem, we leverage a modified Dijkstra’s algorithm to find the minimum time to reach the destination efficiently.

The key idea here is to focus on the maximum height (time) along the path to the destination.

By choosing the path with the smallest maximum height, we ensure that we reach the destination as quickly as possible.

Related Interview Questions By Company:

Related Interview Questions By Difficulty:

Related Interview Questions By Category:

Conclusion

In this blog post, we tackled the Swim In Rising Water problem from LeetCode, providing a detailed explanation of the problem statement, constraints, and a Python solution.

We used a modified Dijkstra’s algorithm with a minimum heap to efficiently find the minimum time to reach the bottom-right square while considering the elevation constraints.

If you found this post helpful, please like and engage to support our our platform.

Feel free to comment with any questions, suggestions, or further explanations you might need.

Happy coding!

>