1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
|
#include <iostream>
#include <string>
#include <vector>
#include <stack>
#include <utility>
using namespace std;
using matrix = vector< vector<int> >;
//======================================================================
void floodfill_stack( matrix &grid, int i, int j )
{
int rows = grid.size();
int cols = grid[0].size();
if ( i < 0 || i >= rows || j < 0 || j >= cols ) return;
if ( grid[i][j] ) return;
stack< pair<int,int> > stk;
stk.push( { i, j } );
while ( !stk.empty() )
{
auto p = stk.top(); stk.pop();
i = p.first; j = p.second;
grid[i][j] = 1;
if ( i > 0 && !grid[i-1][j] ) stk.push( { i - 1, j } );
if ( i < rows - 1 && !grid[i+1][j] ) stk.push( { i + 1, j } );
if ( j > 0 && !grid[i][j-1] ) stk.push( { i, j - 1 } );
if ( j < cols - 1 && !grid[i][j+1] ) stk.push( { i, j + 1 } );
}
}
//======================================================================
void floodfill_recursion( matrix &grid, int i, int j )
{
int rows = grid.size();
int cols = grid[0].size();
if ( i < 0 || i >= rows || j < 0 || j >= cols ) return;
if ( grid[i][j] ) return;
grid[i][j] = 1;
floodfill_recursion( grid, i - 1, j );
floodfill_recursion( grid, i + 1, j );
floodfill_recursion( grid, i, j - 1 );
floodfill_recursion( grid, i, j + 1 );
}
//======================================================================
void display( string title, const matrix &grid )
{
cout << title << '\n';
for ( auto row : grid )
{
for ( auto e : row ) cout << e;
cout << '\n';
}
}
//======================================================================
int main()
{
matrix grid = {
{ 0,0,0,0,0,0,0,1,1,1,1 },
{ 0,0,0,0,0,0,1,0,0,0,1 },
{ 0,0,0,0,0,0,1,0,0,0,1 },
{ 0,0,0,0,1,1,0,0,0,0,1 },
{ 0,0,0,0,0,1,0,0,0,0,1 },
{ 0,0,0,0,0,0,1,1,1,1,1 }
};
display( "\nInitial:", grid );
floodfill_stack( grid, 2, 8 );
// floodfill_recursion( grid, 2, 8 );
display( "\nFilled:", grid );
}
//======================================================================
|