Approach
Breadth-first search
For Trapping Rain Water II, 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
- 50 lines of Java from the credited upstream file 407.java.
- The implementation visibly relies on sequence storage, work queue.
- 4 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 trapRainWater(int[][] heightMap) {3 4 record T(int i, int j, int h) {}5 final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};6 final int m = heightMap.length;7 final int n = heightMap[0].length;8 int ans = 0;9 Queue<T> minHeap = new PriorityQueue<>(Comparator.comparingInt(T::h));10 boolean[][] seen = new boolean[m][n];11 12 for (int i = 0; i < m; ++i) {13 minHeap.offer(new T(i, 0, heightMap[i][0]));14 minHeap.offer(new T(i, n - 1, heightMap[i][n - 1]));15 seen[i][0] = true;16 seen[i][n - 1] = true;17 }18 19 for (int j = 1; j < n - 1; ++j) {20 minHeap.offer(new T(0, j, heightMap[0][j]));21 minHeap.offer(new T(m - 1, j, heightMap[m - 1][j]));22 seen[0][j] = true;23 seen[m - 1][j] = true;24 }25 26 while (!minHeap.isEmpty()) {27 final int i = minHeap.peek().i;28 final int j = minHeap.peek().j;29 final int h = minHeap.poll().h;30 for (int[] dir : DIRS) {31 final int x = i + dir[0];32 final int y = j + dir[1];33 if (x < 0 || x == m || y < 0 || y == n)34 continue;35 if (seen[x][y])36 continue;37 if (heightMap[x][y] < h) {38 ans += h - heightMap[x][y];39 minHeap.offer(new T(x, y, h)); 40 } else {41 minHeap.offer(new T(x, y, heightMap[x][y]));42 }43 seen[x][y] = true;44 }45 }46 47 return ans;48 }49}50