733. 图像渲染

1、题目描述

2、题目解析【深度优先搜索

class Solution {
    public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
        //起始点是一个固定的起始值image[sr][sc]
        int currentColor = image[sr][sc];
        //当前值根newColor不一致,则进行染色
        if(currentColor != newColor){
            this.dfs(image, sr, sc, currentColor,newColor);
        }
        return image;
    }
   
    private void dfs(int[][] image, int x, int y, int  currentColor, int newColor){
       if(x < 0 || y < 0 || x > image.length-1 || y > image[0].length-1){
          return;
       }
       //跟初始值一样的数值,才进行染色到最新颜色
       if(image[x][y] != newColor && image[x][y] == currentColor){
          image[x][y] = newColor;
          //然后向四面染色
          dfs(image,x+1,y,currentColor,newColor);
          dfs(image,x-1,y,currentColor,newColor);
          dfs(image,x,y+1,currentColor,newColor);
          dfs(image,x,y-1,currentColor,newColor);  
       }
    }
}

 

复杂度分析

时间复杂度:O(n×m),其中 n 和 m 分别是二维数组的行数和列数。最坏情况下需要遍历所有的方格一次。

空间复杂度:O(n×m),其中 n 和 mm分别是二维数组的行数和列数。主要为栈空间的开销。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值