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
|
#include <iostream>
constexpr int N = 5 ;
using mine_field = bool[N][N] ; // true if it is a mine
using mine_count = int[N][N] ; // count of number of mines in surrounding cells
bool valid_pos( int pos ) { return pos >= 0 && pos < N ; }
bool valid_pos( int row, int col ) { return valid_pos(row) && valid_pos(col) ; }
void reset_counts( mine_count& counts )
{ for( auto& row : counts ) for( int& c : row ) c = 0 ; }
void set_count( const mine_field& fld, mine_count& counts, int row, int col )
{
if( fld[row][col] ) counts[row][col] = -1 ; // dummy count of -1 if it is a mine
else // not a mine, count mines in surrounding cells
{
for( int delta_x : { -1, 0, +1 } )
for( int delta_y : { -1, 0, +1 } )
{
const int x = row+delta_x ;
const int y = col+delta_y ;
if( valid_pos(x,y) ) counts[row][col] += fld[x][y] ; // += 1 if it is a mine
}
}
}
void set_counts( const mine_field& fld, mine_count& counts )
{
reset_counts(counts) ;
for( int row = 0 ; row < N ; ++row )
for( int col = 0 ; col < N ; ++col )
set_count( fld, counts, row, col ) ;
}
void print_fld( const mine_field& fld )
{
for( const auto& row : fld )
{
for( bool v : row ) std::cout << ( v ? 'M' : '.' ) << " " ;
std::cout << "\n\n" ;
}
}
void print_counts( const mine_count& counts )
{
for( const auto& row : counts )
{
// print '*' if it is a mine (if count == -1)
for( int c : row ) std::cout << ( c < 0 ? '*' : char(c+'0') ) << " " ;
std::cout << "\n\n" ;
}
}
int main()
{
const mine_field fld =
{
{ false, true, false, true, false },
{ true, false, false, false, true },
{ false, true, false, true, false },
{ true, false, false, false, true },
{ true, false, false, false, true }
};
print_fld(fld) ;
std::cout << "\n------ counts --------\n\n" ;
mine_count counts{} ;
set_counts( fld, counts ) ;
print_counts(counts) ;
}
|