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相同的邻居开始,一旦周围没有相同的邻居,直接返回就可以

  • 相关阅读:
    [SAM4N学习笔记]UART的使用
    [SAN4N学习笔记]使用SysTick精准延时
    [SAM4N学习笔记]LED点灯程序
    [SAM4N学习笔记]SAM4N工程模板搭建
    C#用大石头Xcode做数据底层注意事项
    C#MVC中@HTML中的方法
    js比较时间大小(时间为以-分割的字符串时)
    C#后台Post提交XML 及接收该XML的方法
    jq对象和DOM对象的互换
    获取和设置HTML标签中的数据
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/12873919.html
Copyright © 2011-2022 走看看