$O(nm×lognm)$
class Solution {
public:
int n, m;
vector<vector<int>> g;
int dx[8] = {-1, -1, 0, 1, 1, 1, 0, -1}, dy[8] = {0, 1, 1, 1, 0, -1, -1, -1};
vector<int> pondSizes(vector<vector<int>>& land) {
g = land;
n = land.size(), m = land[0].size();
vector<int> res;
for (int i = 0; i < n; i ++ ) {
for (int j = 0; j < m; j ++ ) {
if (g[i][j] == 0) {
int cnt = dfs(i, j);
res.push_back(cnt);
}
}
}
sort(res.begin(), res.end());
return res;
}
int dfs(int x, int y) {
int cnt = 1;
g[x][y] = 1;
for (int i = 0; i < 8; i ++ ) {
int a = x + dx[i], b = y + dy[i];
if (a >= 0 && a < n && b >= 0 && b < m && g[a][b] == 0)
cnt += dfs(a, b);
}
return cnt;
}
};