Leetcode 733. Flood Fill

版权声明:博客文章都是作者辛苦整理的,转载请注明出处,谢谢! https://blog.csdn.net/Quincuntial/article/details/83511772

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Flood Fill

2. Solution

  • Version 1
class Solution {
public:
    vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
        int rows = image.size();
        int columns = image[0].size();
        vector<vector<int>> flag(rows, vector<int>(columns));
        int oldColor = image[sr][sc];
        floodFill(image, sr, sc, newColor, oldColor, rows, columns, flag);
        return image;
    }

private:
    void floodFill(vector<vector<int>>& image, int sr, int sc, int& newColor, int& oldColor, int& rows, int& columns, vector<vector<int>>& flag) {
        if(sr < 0 || sr == rows || sc < 0 || sc == columns || image[sr][sc] != oldColor || flag[sr][sc]) {
            return;
        }
        image[sr][sc] = newColor;
        flag[sr][sc] = 1;
        floodFill(image, sr + 1, sc, newColor, oldColor, rows, columns, flag);
        floodFill(image, sr - 1, sc, newColor, oldColor, rows, columns, flag);
        floodFill(image, sr, sc + 1, newColor, oldColor, rows, columns, flag);
        floodFill(image, sr, sc - 1, newColor, oldColor, rows, columns, flag);
    }
};
  • Version 2
class Solution {
public:
    vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
        int rows = image.size();
        int columns = image[0].size();
        int oldColor = image[sr][sc];
        floodFill(image, sr, sc, newColor, oldColor, rows, columns);
        return image;
    }

private:
    void floodFill(vector<vector<int>>& image, int sr, int sc, int& newColor, int& oldColor, int& rows, int& columns) {
        if(sr < 0 || sr == rows || sc < 0 || sc == columns || image[sr][sc] != oldColor || image[sr][sc] == newColor) {
            return;
        }
        image[sr][sc] = newColor;
        floodFill(image, sr + 1, sc, newColor, oldColor, rows, columns);
        floodFill(image, sr - 1, sc, newColor, oldColor, rows, columns);
        floodFill(image, sr, sc + 1, newColor, oldColor, rows, columns);
        floodFill(image, sr, sc - 1, newColor, oldColor, rows, columns);
    }
};

Reference

  1. https://leetcode.com/problems/flood-fill/description/

猜你喜欢

转载自blog.csdn.net/Quincuntial/article/details/83511772