FloodFill算法

 FloodFill算法简介:

在一个有山谷平原低谷的地区,有洪水,然后找出会被洪水淹没的地区。

其实就是在找一个性质相同的连通块

1、图像渲染

733. 图像渲染 - 力扣(LeetCode)

class Solution 
{
    bool visit[51][51];
    int aim;//目标像素
    int init;//原始像素
    int dx[4] = {0,0,1,-1};
    int dy[4] = {1,-1,0,0};
    int m,n;
public:
    vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int color) 
    {
        aim = color;
        init = image[sr][sc];
        if(init == aim) return image;//如果初始像素就等于原始像素,就不用操作
        m = image.size(), n = image[0].size();        
        dfs(image,sr,sc);
        return image;
    }
    void dfs(vector<vector<int>>& image,int i,int j)
    {
        image[i][j] = aim;//将该位置改为aim
        for(int k = 0;k<4;k++)
        {
            int x = i + dx[k], y = j + dy[k];
            if(x >= 0 && x < m && y >= 0 && y < n && !visit[x][y] && image[x][y] == init)//满足条件
            {
                dfs(image,x,y);//就递归进去
            }
        }
    }
};

注意:这道题的话,不需要用visit来记录路径,这个题是可以退回去使用的,我们需要做的只是将像素改变。

并且,我们到达一个“路口”的时候,向不同岔路口进去遍历后,是需要回到当前路口的。如果用visit的话,就回不来了。因为这里只用修改现场,不用恢复。

2、岛屿数量

200. 岛屿数量 - 力扣(LeetCode)

那么其实本题就是找有几块“1”,就可以使用FloodFill算法。

class Solution 
{
    int m,n;
    int res;//统计岛屿数量
    int dx[4] = {0,0,1,-1};//向量表示
    int dy[4] = {1,-1,0,0};
    vector<vector<bool>> visit;//记录走过的陆地,就不能还原现场了
public:
    int numIslands(vector<vector<char>>& grid) 
    {
        m = grid.size(), n = grid[0].size();
        visit = vector<vector<bool>>(m,vector<bool>(n,false));
        for(int i = 0; i < m ;i++)
            for(int j = 0 ;j<
  • 16
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

夹心宝贝

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

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

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

打赏作者

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

抵扣说明:

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

余额充值