Timeline
Timeline
2025-10-03
init
Min-heap, BFS
Problem:
Boundary cells can never hold water
Because water flows away from the boundary, the boundary of the pool is the perimeter of the matrix.Start filling from the shortest boundary
Similar to the ‘barrel effect’, the water level is determined by the lowest boundary. Therefore, we need to dynamically maintain the current lowest boundary height.Algorithm steps (min-heap + BFS)
- Put all boundary cells (the entire perimeter) into a min-heap (priority queue, sorted by height from smallest to largest), and mark them as visited.
- Each time, pop the current lowest cell from the heap, denoted as cell.
- Scan its 4-directional neighbors:
- If the neighbor has not been visited: if the neighbor’s height < cell’s height, it means water can accumulate here, and the amount of water is cell height - neighbor height. Update the neighbor’s ‘effective height’ to max(neighbor height, cell height) (after the water fills up, its height is equivalent to the water surface). Add the neighbor to the heap.
- Repeat until the heap is empty.
Thus, the entire algorithm is equivalent to ‘pouring water inward from the shortest boundary’.
For example
1 | [ |
The outer ring heights are all 5, the middle is 1. Starting from the boundary, the lowest height in the heap is 5. When processing the middle cell, it is found that height 1 is lower than the boundary water level 5 → can hold 4 units of water. Each inner cell holds 4, finally getting 4*4=16.
1 |
|
