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
|
#include <iostream>
#include <set>
#include <utility>
using namespace std;
typedef set<pair<size_t,size_t>> FloodedContainer;
static const size_t N = 5;
void flood( const int grid[N][N], size_t x, size_t y, FloodedContainer & flooded )
{
// (x,y) not in 'flooded' yet?
if ( flooded.count( make_pair(x,y) ) == 0 )
{
flooded.insert( make_pair(x,y) );
// flood valid neighbor points of same value.
const int gridValue = grid[x][y];
if ( x > 0 && grid[x-1][y] == gridValue ) flood( grid, x-1, y, flooded );
if ( y > 0 && grid[x][y-1] == gridValue ) flood( grid, x, y-1, flooded );
if ( x < N-1 && grid[x+1][y] == gridValue ) flood( grid, x+1, y, flooded );
if ( y < N-1 && grid[x][y+1] == gridValue ) flood( grid, x, y+1, flooded );
}
}
int main(void)
{
int grid[N][N] = {
{1,1,3,2,0},
{0,1,0,2,1},
{1,1,0,3,3},
{3,0,3,1,0},
{2,2,2,0,1} };
FloodedContainer flooded;
flood( grid, 4, 0, flooded );
cout << "The number is " << flooded.size() << '.' << endl;
return 0;
}
|