Leetcode|DFS|面试题 16.19. 水域大小

2021-09-22 11:20:57 浏览数 (2)

1 DFS

代码语言:javascript复制
class Solution {
private:
    int row, col, count;
    vector<int> watersize;
public:
    void dfs(vector<vector<int>>& land, int r, int c) {
        if (r < 0 || c < 0 || r >= row || c >= col || land[r][c] != 0) return;
        land[r][c] = 1;
        count  ;
        dfs(land, r   1, c);
        dfs(land, r - 1, c);
        dfs(land, r, c   1);
        dfs(land, r, c - 1);

        dfs(land, r   1, c   1);
        dfs(land, r - 1, c - 1);
        dfs(land, r   1, c - 1);
        dfs(land, r - 1, c   1);
    }

    vector<int> pondSizes(vector<vector<int>>& land) {
        row = land.size();
        col = land[0].size();
        for (int i = 0; i < row; i  ) 
            for (int j = 0; j < col; j  ) {
                if (land[i][j] == 0) {
                    count = 0;
                    dfs(land, i, j);
                    watersize.push_back(count);
                }
            }
        sort(watersize.begin(), watersize.end());
        return watersize;
    }
};
dfs

0 人点赞