zoukankan      html  css  js  c++  java
  • 733. Flood Fill

    An image is represented by a 2-D array of integers, each integer representing the pixel value of the image (from 0 to 65535).

    Given a coordinate (sr, sc) representing the starting pixel (row and column) of the flood fill, and a pixel value newColor, "flood fill" the image.

    To perform a "flood fill", consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color as the starting pixel), and so on. Replace the color of all of the aforementioned pixels with the newColor.

    At the end, return the modified image.

    Example 1:

    Input: 
    image = [[1,1,1],[1,1,0],[1,0,1]]
    sr = 1, sc = 1, newColor = 2
    Output: [[2,2,2],[2,2,0],[2,0,1]]
    Explanation: 
    From the center of the image (with position (sr, sc) = (1, 1)), all pixels connected 
    by a path of the same color as the starting pixel are colored with the new color.
    Note the bottom corner is not colored 2, because it is not 4-directionally connected
    to the starting pixel.
    

    Note:

    • The length of image and image[0] will be in the range [1, 50].
    • The given starting pixel will satisfy 0 <= sr < image.length and 0 <= sc < image[0].length.
    • The value of each color in image[i][j] and newColor will be an integer in [0, 65535].
    class Solution {
        public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
            int m = image.length;
            int n = image[0].length;
            int co = image[sr][sc];
            if(co == newColor) return image;
            DFS(image, sr, sc, newColor, co);
            return image;
        }
        public void DFS(int[][] image, int i, int j, int newColor, int co){
            if(i >= image.length || i < 0 || j >= image[0].length || j < 0 || image[i][j] != co) return;
            image[i][j] = newColor;
            DFS(image,i+1,j, newColor, co);
            DFS(image,i-1,j, newColor, co);
            DFS(image,i,j + 1, newColor, co);
            DFS(image,i,j - 1, newColor, co);
        }
    }

    意思是给一个初始点,找到他所有和他value一样的4个邻居中的点替换成 目标value,然后再在邻居中找,套娃,替换完返回原数组

    典型DFS,上下左右那种,设置好return的边界条件。然后替换,然后继续上下左右dfs,最后返回。

    有一点要注意,他说从sr,sc开始,以及他周围四个和srsc相同的邻居开始,一旦周围没有相同的邻居,直接返回就可以

  • 相关阅读:
    MVC的12种ActionResult介绍以及应用示例【转】
    SQL Server抛出异常信息 RAISERROR
    lambda select和where区别
    JS中的原型对象与构造器
    JS原型的动态性
    关于困惑已久的var self=this的解释
    JS原型对象的问题
    再谈.NET委托(delegate、Func<>)
    在函数作用域嵌套下使用this
    Python 易错点
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/12873919.html
Copyright © 2011-2022 走看看