Skip to main content

Swim in Rising Water Algorithm Solution

Complete Java implementation for finding minimum time to swim from top-left to bottom-right in a rising water grid using binary search and DFS.

The Swim in Rising Water problem requires finding the minimum time to navigate from the top-left to bottom-right cell of a grid where water level rises over time, making some paths inaccessible until the water level reaches a sufficient height.

1. Problem Restatement

Clarifying questions to ask the interviewer:

  1. Can we mutate the input grid, or must we work with a copy?
  2. What are the constraints on grid dimensions (e.g., max size)?
  3. Are we guaranteed that there's always a valid path from (0,0) to (n-1,n-1)?
  4. Should we return the minimum time value or just the minimum time needed?
  5. Can we assume all grid values are non-negative integers?

Restatement of the problem: We're given an n×n grid where each cell contains a height value. We start at the top-left corner (0,0) and need to reach the bottom-right corner (n-1,n-1). The water level rises over time, and we can only move to a cell if its height is less than or equal to the current water level. We want to find the minimum time at which a valid path exists from start to end.

Input/Output specification:

  • Input: 2D integer array grid of size n×n where grid[i][j] represents the height at position (i,j)
  • Output: Integer representing the minimum time (water level) required to have a valid path from (0,0) to (n-1,n-1)

Constraints:

  • Grid is square: n×n where 1 ≤ n ≤ 50
  • Each cell contains a non-negative integer height value
  • Movement is allowed in 4 directions (up, down, left, right)
  • Path must exist from (0,0) to (n-1,n-1)

Assumptions:

  • The grid is valid and connected (at least one path exists)
  • We can move to adjacent cells only if their height ≤ current water level
  • Time increases monotonically (water level never decreases)
  • The answer will always be achievable

Data shape and hidden structure: The problem exhibits a monotonic property where increasing water level can only add more valid paths, never remove them. This suggests a binary search or Dijkstra's approach could be effective. The grid forms a graph where each cell is a node and edges exist between adjacent cells, with edge weights representing the height difference.

2. Pattern Recognition

The most likely pattern here is Binary Search on Answer combined with Graph Traversal (BFS/DFS).

The wording that signals this pattern includes:

  • "Swim in Rising Water" - suggests we're looking for a threshold value (water level) where a path becomes possible
  • The problem asks us to find the minimum time (water level) when we can reach from top-left to bottom-right
  • We're essentially searching for the optimal "cut-off" value where a connectivity condition is met

This problem fits the Binary Search on Answer pattern because:

  1. We're looking for a minimum value (the earliest time when path exists)
  2. The answer space is bounded (0 to max(grid) in the worst case)
  3. For any given water level, we can efficiently determine if a path exists using graph traversal
  4. If a path exists at level X, it also exists at any higher level - this monotonic property enables binary search

The core insight is that we can binary search on the water level, and for each candidate level, use BFS/DFS to check if there's a valid path from (0,0) to (n-1,n-1). The first level where such a path exists is our answer.

This is fundamentally different from typical graph problems because we're not just finding a path - we're optimizing the condition under which that path becomes possible. The key is recognizing that we can treat the water level as a binary search space where each "guess" requires a graph connectivity check.

The pattern is also reminiscent of Minimum Spanning Tree problems in that we're optimizing a parameter (water level) to satisfy a constraint (path existence), but the specific structure here makes binary search more appropriate than MST algorithms.

3. Approach Evolution

My first instinct is to think about this as a pathfinding problem where we want to find the minimum time when a path exists from top-left to bottom-right. But that's O(n²) because we'd have to check every possible time threshold, and for each we'd need to do a graph traversal.

Let me think about how to optimize this. I notice that if I maintain a constraint on the maximum water level encountered along any path, I can reduce it to O(n log n) by using binary search on the answer combined with a graph traversal like BFS or DFS.

The key insight is that we're looking for the minimum time T such that there exists a path from (0,0) to (n-1,n-1) where every cell in the path has water level ≤ T. This suggests a binary search approach on the answer space.

If I fix some time T, I can check if there's a valid path by doing a BFS/DFS on cells with water level ≤ T. Since the water levels are in [0, 10^9], and we have at most n² cells, the binary search will take O(log(10^9)) = O(30) steps, and each BFS/DFS takes O(n²) time.

But wait, I can do better than that. The problem is asking for the minimum time to reach the destination, which means I want the maximum water level encountered on the optimal path. This is actually a min-max problem - minimize the maximum value along any valid path.

This suggests using a priority queue (min-heap) with Dijkstra's algorithm, where I prioritize paths by the maximum water level encountered so far. This way, I can find the minimum time needed to reach the destination.

Actually, let me reconsider. The problem is asking for the earliest time when we can swim from (0,0) to (n-1,n-1). The water level increases over time, so we want the minimum time T such that a path exists when all cells have water level ≤ T.

So I can binary search on T, and for each T check if a path exists using BFS. But there's an even better approach: I can use Union-Find (Disjoint Set Union) with a clever ordering.

The most efficient approach is to use binary search + BFS, but let me think about the optimal one. The key insight is that we want to find the minimum time T such that there's a connected path from (0,0) to (n-1,n-1).

I'll go with the binary search + BFS approach because:

  1. It's intuitive and easy to verify correctness
  2. The time complexity is acceptable: O(n² log(max_water_level))
  3. It's easy to implement and debug

The invariant I need to maintain is that at any time T, if there's a path from (0,0) to (n-1,n-1), then all cells in that path have water level ≤ T. I'll binary search on T, and for each candidate T, I'll run BFS to see if a path exists in the subgraph where all water levels ≤ T.

This approach works because:

  • The answer is bounded between the minimum and maximum water levels
  • If there's a valid path at time T, there's also a valid path at any later time
  • If there's no valid path at time T, there's also no valid path at any earlier time
  • This gives us the monotonic property needed for binary search

Let me implement the binary search + BFS solution:

// Binary search on time T, for each T check if path exists using BFS
// Time complexity: O(n² log(max_water_level))
// Space complexity: O(n²) for visited array

This is clean, efficient, and handles the monotonic nature of the problem well. The binary search reduces the search space from 10^9 to about 30 steps, and BFS efficiently determines connectivity for each threshold.

4. Data Structure Choice

For this problem, I'll use a min-heap (PriorityQueue) as my primary data structure, combined with a 2D boolean visited array to track explored cells.

The min-heap is essential because:

  • It allows us to always process the cell with the minimum water level first
  • This greedy approach ensures we find the optimal path where the maximum water level encountered is minimized
  • Java's PriorityQueue naturally maintains elements in ascending order, which aligns perfectly with our requirement to explore lower water levels first

The visited array is necessary because:

  • It prevents us from revisiting cells during our path exploration
  • It ensures we don't get stuck in cycles or redundant processing
  • It maintains O(1) lookup time for checking if a cell has been processed

Additional helper structures:

  • 2D boolean array: Used for visited tracking with O(1) access time
  • Integer array: For directional movement (up, down, left, right) to simplify neighbor exploration

The time complexity of heap operations is O(log n) for insertion and extraction, while the visited array provides O(1) lookups. This combination gives us optimal performance for our path-finding algorithm.

The choice of min-heap over other data structures like regular queues or stacks is crucial - a regular queue would process cells in insertion order rather than water level order, and a stack would cause us to explore deeper paths first, neither of which would guarantee the optimal solution for minimizing maximum water level.

5. Algorithm Walkthrough

Let me trace through the algorithm with a concrete example to show how it works step by step.

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

Step 1: Initialize data structures

  • minHeap with starting point: new Cell(0, 0, 0) (row=0, col=0, elevation=0)
  • visited set containing (0,0) to avoid revisiting

Step 2: Process the heap

  • Pop Cell(0, 0, 0) from heap (elevation 0)
  • Check neighbors: (0,1) at elevation 2 and (1,0) at elevation 1
  • Add both to heap with max elevation: Cell(0, 1, 2) and Cell(1, 0, 1)
  • Mark (0,0) as visited

Step 3: Continue processing

  • Pop Cell(1, 0, 1) (elevation 1) - this is the minimum elevation needed to reach it
  • Check neighbors: (1,1) at elevation 3 (already visited)
  • Check (0,0) - already visited
  • Add Cell(1, 1, max(1,3)) = Cell(1, 1, 3) to heap

Step 4: Final processing

  • Pop Cell(1, 1, 3) from heap - we've reached the destination
  • Return 3 as the minimum time needed

Key insight: The algorithm maintains that at any point, we're always exploring the path that requires the minimum possible water level to reach a cell. This greedy approach ensures we find the optimal solution.

Edge case handling:

  • When we have a single cell grid, we return its elevation immediately
  • When we reach the destination, we return the maximum elevation encountered on that path

The algorithm terminates correctly because we're guaranteed to find a path from top-left to bottom-right, and we always explore the most "cost-effective" path first.

6. Java Solution

import java.util.*;

public class SwimInRisingWater {
    
    public int swimInWater(int[][] grid) {
        // Binary search on the answer - time needed to reach destination
        int left = grid[0][0];
        int right = grid.length * grid[0].length - 1;
        int result = right;
        
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (canReach(grid, mid)) {
                result = mid;
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        
        return result;
    }
    
    private boolean canReach(int[][] grid, int time) {
        // BFS to check if we can reach from (0,0) to (n-1,n-1) at given time
        int n = grid.length;
        if (grid[0][0] > time) return false;
        
        Queue<int[]> queue = new LinkedList<>();
        boolean[][] visited = new boolean[n][n];
        
        queue.offer(new int[]{0, 0});
        visited[0][0] = true;
        
        int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
        
        while (!queue.isEmpty()) {
            int[] current = queue.poll();
            int row = current[0];
            int col = current[1];
            
            if (row == n - 1 && col == n - 1) {
                return true;
            }
            
            for (int[] dir : directions) {
                int newRow = row + dir[0];
                int newCol = col + dir[1];
                
                // Check bounds and if already visited
                if (newRow >= 0 && newRow < n && newCol >= 0 && newCol < n && !visited[newRow][newCol]) {
                    // Can only move to cell if its height is <= time
                    if (grid[newRow][newCol] <= time) {
                        visited[newRow][newCol] = true;
                        queue.offer(new int[]{newRow, newCol});
                    }
                }
            }
        }
        
        return false;
    }
}

This solution uses binary search on the answer combined with BFS to find the minimum time needed to swim from top-left to bottom-right. The key insight is that we can binary search on the time parameter, and for each time value, check if a path exists using BFS. This approach efficiently handles the constraint that we can only move to cells with elevation ≤ current time.

7. Complexity Analysis

Time Complexity: O(n² log n)

The solution uses binary search over the answer space, which takes O(log(maxHeight - minHeight)) time. In the worst case, this is O(log n²) = O(2 log n) = O(log n). For each binary search iteration, we perform a BFS/DFS to check connectivity, which takes O(n²) time where n is the grid dimension. Therefore, the overall time complexity is O(n² log n).

Space Complexity: O(n²)

The space complexity comes from:

  • The visited boolean array of size n×n for tracking explored cells during BFS
  • The queue used in BFS, which can contain at most n² elements in the worst case (when all cells are reachable)
  • Additional space for storing the grid and other auxiliary variables

The space complexity is dominated by the visited array and BFS queue, both requiring O(n²) space.

Why these bounds are correct:

The binary search range is bounded by the difference between maximum and minimum heights in the grid, which is at most n² for an n×n grid with values from 0 to n²-1. The BFS traversal visits each cell at most once, making it O(n²) per search iteration.

Optimality:

This solution is near-optimal for the given constraints. The O(n² log n) complexity is reasonable since we must examine each cell at least once and binary search provides the best approach for finding the minimum threshold. A better solution would require more sophisticated graph algorithms or optimizations that aren't available for this specific problem structure. The solution is optimal in terms of the computational complexity class and practical performance for typical input sizes.

8. Edge Cases & Pitfalls

Empty and Minimal Inputs

  • Empty grid: An empty 0x0 grid should return 0 as there are no cells to traverse
  • Single cell grid: A 1x1 grid should return the elevation of that single cell
  • 2x2 grid: The most basic non-trivial case with four cells

Duplicate Values and Repeated States

  • Identical elevations: Multiple cells with the same elevation can create ambiguous paths in algorithms that don't properly handle visited states
  • Cyclic dependencies: When traversing to cells with the same elevation, ensure we don't get stuck in cycles

Boundary Conditions

  • Water level at 0: When the water level is at 0, we can only move to cells with elevation 0 or less
  • Water level higher than all elevations: The solution should handle cases where water level exceeds maximum elevation in grid
  • Boundary cell elevations: The starting point (0,0) and ending point (n-1,n-1) must be reachable

Common Implementation Mistakes

  • Incorrect visited tracking: Not properly marking cells as visited during DFS/BFS can lead to infinite loops or incorrect pathfinding
  • Wrong priority queue ordering: In Dijkstra's approach, using wrong comparator can cause incorrect minimum water level calculation
  • Off-by-one errors in grid dimensions: Misreading grid dimensions can cause index out of bounds exceptions
  • Not handling water level as threshold: Confusing elevation values with the actual water level needed to traverse
  • State management in graph traversal: Not properly maintaining state when backtracking or reusing visited arrays

Implementation-specific Pitfalls

  • Integer overflow: When computing water levels, ensure we handle large elevation differences properly
  • Array bounds checking: In BFS/DFS approaches, always validate array indices before accessing grid elements
  • Queue vs Stack confusion: Using stack instead of queue in BFS can change the traversal order and affect correctness
  • Memory allocation: For large grids, ensure proper memory management to avoid stack overflow in recursive approaches

9. Alternative Approaches

There are several alternative approaches to solving the Swim in Rising Water problem, each with different trade-offs:

Binary Search + BFS/DFS: Instead of using a priority queue, we can binary search on the answer (water level). For each candidate water level, we check if a path exists from (0,0) to (n-1,n-1) using BFS/DFS. This approach has O(log(max_height) × n²) time complexity but uses simpler graph traversal techniques.

Union-Find (Disjoint Set): We can process cells in order of increasing water level and union adjacent cells that are "swimmable" (water level ≤ current water level). The first time we can connect the top-left and bottom-right cells, we've found our answer. This approach has O(n² log n) time complexity but is conceptually elegant for connectivity problems.

Dijkstra's Algorithm with Modified Edge Weights: Rather than using a priority queue to minimize maximum water level, we can think of this as finding the minimum cost path where each edge's cost is the maximum water level encountered on that path. This is essentially Dijkstra's algorithm with a different cost function.

The chosen solution using priority queue (min-heap) is preferred because:

  1. It's more intuitive - we're always exploring the path with minimum required water level
  2. It has optimal time complexity O(n² log n) which matches the best of alternatives
  3. It's easier to understand and debug than union-find or binary search approaches
  4. The min-heap naturally handles the "minimum maximum" requirement efficiently

The main trade-off is that while binary search + BFS might be more familiar to some engineers, the priority queue approach is more direct and efficient for this specific problem structure.

10. Test Cases

// Test case 1: Basic case with clear path
int[][] grid1 = {{0, 2}, {1, 3}};
// Expected: 3
// Path: (0,0) -> (1,0) -> (1,1) with water level 3

// Test case 2: Single cell grid
int[][] grid2 = {{0}};
// Expected: 0

// Test case 3: Grid with higher elevation path
int[][] grid3 = {{0, 1, 2}, {1, 2, 3}, {2, 3, 4}};
// Expected: 4
// Path: (0,0) -> (1,1) -> (2,2) with water level 4

// Test case 4: Complex path requiring higher water level
int[][] grid4 = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}};
// Expected: 8
// Path: (0,0) -> (1,0) -> (2,0) -> (2,1) -> (2,2) with water level 8

// Test case 5: Edge case - empty grid (if allowed)
int[][] grid5 = {};
// Expected: 0 or handle appropriately

// Test case 6: Grid with duplicate values
int[][] grid6 = {{1, 1, 1}, {1, 1, 1}, {1, 1, 1}};
// Expected: 1

The test cases cover:

  • Basic functionality with clear optimal paths
  • Edge cases like single element grids
  • Grids where the optimal path isn't the one with lowest maximum elevation
  • Duplicate values that could confuse path selection logic
  • Boundary conditions for grid dimensions

Each test case validates different aspects of the algorithm's behavior and ensures correct handling of various input configurations.

11. Final Summary

The core insight is that this problem requires finding the minimum time to reach from top-left to bottom-right in a grid where water level rises over time, making some paths unavailable. The solution uses binary search on the answer combined with BFS/DFS to efficiently determine the minimum time needed.

This approach works because:

  1. The answer space is bounded (0 to max grid value) and monotonically increasing
  2. For any given time threshold, we can determine if a path exists using graph traversal
  3. Binary search allows us to find the minimum valid threshold efficiently

The solution is optimal in both time and space complexity, with O(n² log(maxVal)) time and O(n²) space. The key efficiency comes from avoiding explicit time tracking by leveraging the monotonic property of water level rise, making it a clean and scalable approach for this class of "minimum threshold" problems.

Was this article helpful?

Topics in this article

More from DSA Problems

  • DSA Problems

    Path With Minimum Effort Algorithm Solution

    Complete Java implementation for finding minimum effort path in a grid using binary search and Dijkstra's algorithm approaches.

  • DSA Problems

    Flood Fill Algorithm Implementation and Analysis

    Complete Java solution for flood fill algorithm with BFS/DFS approaches, time complexity analysis, and practical implementation considerations for FAANG interviews.

  • DSA Problems

    Max Area of Island Java Solution

    Complete Java implementation for finding maximum area of island in 2D grid using DFS and BFS approaches with time and space complexity analysis.

Stay in the Loop

Get curated DSA patterns, coding problems, frontend and backend LLD/HLD, and AI/ML System Design insights delivered straight to your inbox. No spam, just focused interview and engineering content.