水域大小(DFS)

 该题有点像做过的“岛屿数量”,也是标准的模板题,按照模板Go!!!!!!!!!!!!!

岛屿数量(DFS / BFS)_ZZZWWWFFF_的博客-CSDN博客

 

class Solution {
public:
    vector<int> v;
    int tx,ty,n,m,c=0,nextt[8][2]={{0,1},{1,1},{1,0},{1,-1},{0,-1},{-1,-1},{-1,0},{-1,1}};
        int dfs(vector<vector<int>>& land,int x,int y)
    {
        if(land[x][y]==0)
        {
            land[x][y]=-1;//走过的地方做记号
            c++;//水域数
            for(int i=0;i<8;i++)
            {
                tx=x+nextt[i][0];
                ty=y+nextt[i][1];
                if(tx<0||ty<0||tx>=n||ty>=m)
                {
                    continue;
                }
                dfs(land,tx,ty);
            }
        }
        return c;
    }
    vector<int> pondSizes(vector<vector<int>>& land) {
        n=land.size();
        m=land[0].size();
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<m;j++)
            {
                if(land[i][j]==0)//遇到水域就进入搜索并且计算水域数量
                {
                    c=0;
                    v.push_back(dfs(land,i,j));
                }
            }
        }
        sort(v.begin(),v.end());排序
        return v;

    }

};

下面是我在题解中看到的一份我觉得不错的题解,分享给大家(大致思路差不多) 

class Solution {
public:
    vector<int> ret;
    int ans;
    vector<int> pondSizes(vector<vector<int>>& land) {
        for(int i=0;i<land.size();i++){
            for(int j=0;j<land[i].size();j++){
                if(!land[i][j]){
                    ans = 0;
                    dfs(land, i, j);
                    ret.push_back(ans);
                }
             
            }
        }
        sort(ret.begin(),ret.end());
        return ret;
    }
    void dfs(vector<vector<int>>& land, int x, int y){
        if(x < 0 || x >= land.size() || y < 0 || y >= land[x].size() || land[x][y]){
            return;
        }
        if(!land[x][y]){
            ans++;
        }
        land[x][y]--;//走过做记号
        dfs(land, x-1, y);
        dfs(land, x-1, y-1);
        dfs(land, x-1, y+1);
        dfs(land, x, y-1);
        dfs(land, x, y+1);
        dfs(land, x+1, y-1);
        dfs(land, x+1, y);
        dfs(land, x+1, y+1);
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ZZZWWWFFF_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值