You have an integer matrix representing a plot of land, where the value at that location represents the height above sea level. A value of zero indicates water. A pond is a region of water connected vertically, horizontally, or diagonally. The size of the pond is the total number of connected water cells. Write a method to compute the sizes of all ponds in the matrix.
Ponds are 8-connected zeros; report sorted areas. Union-find or BFS both work; one grid pass is enough.
Each unused \(0\) starts a DFS that counts and paints cells nonzero so they are not revisited.
The eight neighbors are the \([-1,1]\times[-1,1]\) box (the center is already painted). Sort the areas at the end.
We can traverse each point \((i, j)\) in the integer matrix \(land\). If the value of the point is \(0\), we start a depth-first search from this point until we reach a point with a non-zero value. The number of points searched during this process is the size of the pond, which is added to the answer array.
Note: To avoid duplicate searches, we set the value of the searched points to \(1\).
Finally, we sort the answer array to obtain the final answer.
The time complexity is \(O(m \times n \times \log (m \times n))\), and the space complexity is \(O(m \times n)\). Here, \(m\) and \(n\) are the number of rows and columns in the matrix \(land\), respectively.