Leetcode 733. Flood Fill

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

1. Description

Leetcode 733. Flood Fill_第1张图片
Flood Fill

2. Solution

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

private:
    void floodFill(vector>& image, int sr, int sc, int& newColor, int& oldColor, int& rows, int& columns, vector>& 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> floodFill(vector>& 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>& 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/

你可能感兴趣的:(Leetcode 733. Flood Fill)