Leetcode每日一題:面試題16.19.水域大小

Taco_Tuesdayyy發表於2020-11-09

在這裡插入圖片描述
簡單的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;
}

相關文章