面试题 16.19. 水域大小

你有一个用于表示一片土地的整数矩阵land,该矩阵中每个点的值代表对应地点的海拔高度。若值为0则表示水域。由垂直、水平或对角连接的水域为池塘。池塘的大小是指相连接的水域的个数。编写一个方法来计算矩阵中所有池塘的大小,返回值需要从小到大排序。

示例:

输入:
[
[0,2,1,0],
[0,1,0,1],
[1,1,0,1],
[0,1,0,1]
]
输出: [1,2,4]
提示:

0 < len(land) <= 1000
0 < len(land[i]) <= 1000

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/pond-sizes-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

借鉴大佬的方法:

class Solution {
private:
    vector<int>res;
    int dir[8][2] = {{1,0},{-1,0},{0,1},{0,-1},{1,-1},{1,1},{-1,1},{-1,-1}};
    int row,col;
public:
    int dfs(vector<vector<int>>& land, int i,int j){
        if(i<0||i>=row||j<0||j>=col||land[i][j]!=0){
            return 0;
        }
        land[i][j]=1;
        int area = 1;
        for(int t=0;t<8;t++){
            int xx = i + dir[t][0];
            int yy = j + dir[t][1];
            area += dfs(land,xx,yy);
        }
        return area;
    }
    vector<int> pondSizes(vector<vector<int>>& land) {
        if(land.empty()||land[0].empty()){
            return {};
        }
        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){
                    res.push_back(dfs(land,i,j));
                }
            }
        }
        sort(res.begin(),res.end());
        return res;
    }
};

这是自己的解法

class Solution {
private:
    vector<int>res;
    int dir[8][2] = {{1,0},{-1,0},{0,1},{0,-1},{1,-1},{1,1},{-1,1},{-1,-1}};
    int row,col;
public:
    void dfs(vector<vector<int>>& land, int i,int j,int&k){
        if(i<0||i>land.size()-1||j<0||j>land[0].size()-1||land[i][j]!=0){
            return;
        }
        land[i][j] = 1;
        k++;
        for(int t=0;t<8;t++){
            int xx = i + dir[t][0];
            int yy = j + dir[t][1];
            dfs(land,xx,yy,k);
            // if(land[xx][yy]==0){
            //     //land[xx][yy] = 1;
            //     //k++;
            //     dfs(land,xx,yy,k);
            // }
        }
        return;
    }
    vector<int> pondSizes(vector<vector<int>>& land) {
        if(land.empty()){
            return {};
        }
        int r = land.size();
        int c = land[0].size();
        int nums = 0;
        for(int i=0;i<r;i++){
            for(int j=0;j<c;j++){
                nums = 0;
                if(land[i][j]==0){
                    dfs(land,i,j,nums);
                    res.push_back(nums);
                }
            }
        }
        sort(res.begin(),res.end());
        return res;
    }
};
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值