• 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);
            }
        }
    };
    
  • 相关阅读:
    安装vue-cli最新版后,无法使用console方法的解决办法
    使用yarn 安装 vue.js devtools(2020.1.6)
    在路由切换后 将滚动条置顶
    标签页 elementUI 激活时的颜色 怎样改 很坑爹!
    页面滚动鼠标产生动画 wow.js 在vue中
    CSS多行文本溢出隐藏,显示省略号
    ... 扩展运算符
    this的指向的一些问题
    用for循环和用for-in循环遍历数组最大的区别
    数组的indexOf、forEach、map、filter、方法的理解
  • 原文地址:https://www.cnblogs.com/renleimlj/p/8046406.html
Copyright © 2020-2023  润新知