zoukankan      html  css  js  c++  java
  • LN : leetcode 733 Flood Fill

    lc 733 Flood Fill


    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].

    DFS Accepted

    这道题是非常简单的dfs算法题,对于当前点,如果其原始值等于image[sr][sc]的原始值,那么将其值替换为newColor,并向其四个方向继续做dfs,直到遇到边界或者下一个原始值不等于image[sr][sc]的原始值。注意:如果image[sr][sc]的原始值就等于newColor的话,那直接返回image,不用做洪泛。

    class Solution {
    public:
        vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
            int color = image[sr][sc];
            if (color != newColor) dfs(image, color, newColor, sr, sc);
            return image;
        }
        void dfs(vector<vector<int>>& image, int color, int n, int sr, int sc) {
            if (image[sr][sc] == color) {
                image[sr][sc] = n;
                if (sr - 1 >= 0) dfs(image, color, n, sr-1, sc);
                if (sc - 1 >= 0) dfs(image, color, n, sr, sc-1);
                if (sr + 1 < image.size()) dfs(image, color, n, sr+1, sc);
                if (sc + 1 < image[0].size()) dfs(image, color, n, sr, sc+1);
            }
        }
    };
    
  • 相关阅读:
    用iText5-2-其他类型PDF
    用iText5-1-生成PDF
    UML介绍-2.3-StarUML的时序图
    UML介绍-2.2-StarUML的类图
    OOAD 面向对象的分析与设计
    激励自己的话
    UML工具-1-StarUML下载及破解
    A1002 字符串长度
    A1001 整除问题
    剑桥雅思写作高分范文ESSAY10
  • 原文地址:https://www.cnblogs.com/renleimlj/p/8046406.html
Copyright © 2011-2022 走看看