Implement Flood Fill algorithm

Given a 2-D matrix representing an image, a location of a pixel in the screen, and a color C, replace the color of the given pixel and all adjacent same-colored pixels with C.

For example, given the following matrix, and location pixel of (2, 2), and 'G' for green:

B B W
W W W
W W W
B B B

Becomes

B B G
G G G
G G G
B B B

Example:

Input:  image = {{'B', 'B', 'W'}, {'W', 'W', 'W'}, {'W', 'W', 'W'}, {'B','B','B'}}
Output: [[B, B, G],[G, G, G],[G, G, G],[B, B, B]]

Approach

C++

#include <bits/stdc++.h>
using namespace std;

void dfs(vector<vector<char>> &imageint x
int ychar prevColorchar newColor)
{
    //check if current cell is valid or not
    if (x < 0 || x >= image.size() || y < 0 || y >= image[0].size())
        return;

    //if current cell color is not same as the
    //prev color
    if (image[x][y] != prevColor)
        return;

    //if current cell color is same as new color
    if (image[x][y] == newColor)
        return;

    //update current cell color to new color
    image[x][y] = newColor;

    //call for down
    dfs(imagex + 1yprevColornewColor);

    //call for up
    dfs(imagex - 1yprevColornewColor);

    //call for right
    dfs(imagexy + 1prevColornewColor);

    //call for left
    dfs(imagexy - 1prevColornewColor);
}
vector<vector<char>> floodFill(vector<vector<char>> &image
int srint scchar newColor)
{
    char prevColor = image[sr][sc];
    dfs(imagesrscprevColornewColor);
    return image;
}

int main()
{
    vector<vector<char>> image = {{'B''B''W'},
                                 {'W''W''W'},
                                 {'W''W''W'},
                                 {'B','B','B'}};
    int sr = 2sc = 2;
    char  newColor = 'G';
    image = floodFill(imagesrscnewColor);
    cout << "[";
    for (int i = 0i < image.size(); i++)
    {
        cout << "[";
        for (int j = 0j < image[i].size(); j++)
        {
            cout << image[i][j];
            if (j != image[i].size() - 1)
                cout << ", ";
        }
        cout << "]";
        if (i != image.size() - 1)
            cout << ",";
    }
    cout << "]";
    return 0;
}


No comments:

Post a Comment