简单的DFS
//八个方位
const int dx[8] = {1, -1, 0, 0, -1, -1, 1, 1};
const int dy[8] = {0, 0, 1, -1, -1, 1, 1, -1};
static bool cmp(int a, int b)
{
return a < b;
}
//经过(x,y)
void dfs(vector<vector<int>> &land, int x, int y, int &count)
{
//个数+1,并将此点置为已访问
count++;
land[x][y] = 1;
int lenX = land.size(), lenY = land[0].size();
for (int k = 0; k < 8; k++)
{
int newX = x + dx[k], newY = y + dy[k];
if (newX < 0 || newX >= lenX || newY < 0 || newY >= lenY || land[newX][newY])
{
continue;
}
dfs(land, newX, newY, count);
}
}
vector<int> pondSizes(vector<vector<int>> &land)
{
int lenX = land.size(), lenY = land[0].size();
vector<int> res;
for (int i = 0; i < lenX; i++)
{
for (int j = 0; j < lenY; j++)
{
if (land[i][j] == 0)
{
int count = 0;
dfs(land, i, j, count);
res.push_back(count);
}
}
}
sort(res.begin(), res.end(), cmp);
return res;
}