Approach
Breadth-first search
For Swim in Rising Water, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 34 lines of Java from the credited upstream file 778.java.
- The implementation visibly relies on sequence storage, work queue.
- 2 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int swimInWater(int[][] grid) {3 final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};4 final int n = grid.length;5 int ans = grid[0][0];6 Queue<int[]> minHeap = new PriorityQueue<>(Comparator.comparingInt(a -> a[0])) {7 { offer(new int[] {grid[0][0], 0, 0}); } 8 };9 boolean[][] seen = new boolean[n][n];10 seen[0][0] = true;11 12 while (!minHeap.isEmpty()) {13 final int height = minHeap.peek()[0];14 final int i = minHeap.peek()[1];15 final int j = minHeap.poll()[2];16 ans = Math.max(ans, height);17 if (i == n - 1 && j == n - 1)18 break;19 for (int[] dir : DIRS) {20 final int x = i + dir[0];21 final int y = j + dir[1];22 if (x < 0 || x == n || y < 0 || y == n)23 continue;24 if (seen[x][y])25 continue;26 minHeap.offer(new int[] {grid[x][y], x, y});27 seen[x][y] = true;28 }29 }30 31 return ans;32 }33}34