• 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);
            }
        }
    };
    
  • 相关阅读:
    媒介管理系统权限设计方案
    document.ready和window.onload区别,顺带jQuery的ready方法
    nvm管理node版本
    async await一些小结
    Git学习
    详解JavaScript中的正则表达式
    JavaScript中的事件循环机制跟函数柯里化
    前端面试遇到的问题
    ES6在工作中会用到的核心知识点讲解
    JavaScript中的事件委托机制跟深浅拷贝
  • 原文地址:https://www.cnblogs.com/renleimlj/p/8046406.html
Copyright © 2020-2023  润新知