Skip to content

Instantly share code, notes, and snippets.

@leenalens
Created July 9, 2020 07:35
#include<vector>
#include<iostream>
using namespace std;
void floodFill(vector<vector<int>>&grid, int x, int y, int oldColor, int newcolor)
{
//check boundary conditions
if (x < 0 || y < 0 || x >= grid.size() || y >= grid.size())
return;
//check if current point is previouscolor
if (grid[x][y] != oldColor)
return;
if (grid[x][y] == newcolor)
return;
grid[x][y] = newcolor;
//left
floodFill(grid,x-1,y,oldColor, newcolor);
//right
floodFill(grid, x +1, y, oldColor, newcolor);
//top
floodFill(grid, x, y -1, oldColor, newcolor);
//bottom
floodFill(grid, x, y + 1, oldColor, newcolor);
}
void printgrid(vector<vector<int>>&grid)
{
for (int x = 0; x < grid.size(); x++)
{
for (int y = 0; y < grid.size(); y++)
{
cout << grid[x][y];
}
cout << endl;
}
}
int main()
{
vector<vector<int>>grid =
{
{ 1, 1, 1, 1, 1, 1, 1, 1 },
{ 1, 1, 1, 1, 1, 1, 0, 0 },
{ 1, 0, 0, 1, 1, 0, 1, 1 },
{ 1, 2, 2, 2, 2, 0, 1, 0 },
{ 1, 1, 1, 2, 2, 0, 1, 0 },
{ 1, 1, 1, 2, 2, 2, 2, 0 },
{ 1, 1, 1, 1, 1, 2, 1, 1 },
{ 1, 1, 1, 1, 1, 2, 2, 1 },
};
int x = 4;
int y = 4;
printgrid(grid);
//convert all 2s to 9
floodFill(grid,x,y,grid[x][y],9);
printgrid(grid);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment