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);
            }
        }
    };
    
  • 相关阅读:
    Leetcode#129 Sum Root to Leaf Numbers
    Leetcode#15 3Sum
    Leetcode#16 3Sum Closest
    Leetcode#127 Word Ladder
    Leetcode#2 Add Two Numbers
    Leetcode#18 4Sum
    vue.js入门(3)——组件通信
    vue.js慢速入门(2)
    vue 基础介绍
    vue.js中v-for的使用及索引获取
  • 原文地址:https://www.cnblogs.com/renleimlj/p/8046406.html
Copyright © 2011-2022 走看看