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 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
|
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
#include <queue>
#include <utility>
using namespace std;
//----------------------------------------------------------
class Game
{
vector<string> board;
vector< vector<int> > F;
public:
void readInput( istream &in );
void fill();
void drawSolution( int W = 1 );
};
//--------------
void Game::readInput( istream &in )
{
board.clear();
for ( string line; getline( in, line ); ) board.push_back( line );
}
//--------------
void Game::drawSolution( int W )
{
for ( auto &row : F )
{
for ( int e : row )
{
if ( e < 0 ) cout << setw( W ) << '.';
else cout << setw( W ) << e;
}
cout << '\n';
}
}
//--------------
void Game::fill()
{
const vector< pair<int,int> > jp = { {-1,-1}, {-1,0}, {-1,1}, {0,-1}, {0,1}, {1,-1}, {1,0}, {1,1} };
int rows = board.size(), cols = board[0].size();
queue< pair<int,int> > Q;
F = vector< vector<int> >( rows, vector<int>( cols, -99 ) );
// Set starting points (as 0) and barriers (as -1)
for ( int i = 0; i < rows; i++ )
{
for ( int j = 0; j < cols; j++ )
{
if ( board[i][j] == 'A' )
{
F[i][j] = 0;
Q.push( { i, j } );
}
else if ( board[i][j] == 'X' )
{
F[i][j] = -1;
}
}
}
// Check adjacent points to current front-of-queue
while( !Q.empty() )
{
auto pr = Q.front(); Q.pop();
int i = pr.first, j = pr.second;
int nextValue = F[i][j] + 1;
for ( int n = 0; n < jp.size(); n++ )
{
int ii = i + jp[n].first, jj = j + jp[n].second; // adjacent point
if ( ii < 0 || ii >= rows || jj < 0 || jj >= cols ) continue; // if outside domain then ignore
if ( F[ii][jj] < -1 ) // not yet set
{
F[ii][jj] = nextValue; // set or improve value
Q.push( { ii, jj } ); // add to current front line
}
}
}
}
//----------------------------------------------------------
int main()
{
// ifstream in( "input.txt" ); // for real
istringstream in( "..............\n" // for demo
"..............\n"
"..............\n"
"..............\n"
".......X......\n"
".......X......\n"
"...A...X......\n"
"...A...X......\n"
".......X......\n"
".......X......\n" );
Game G;
G.readInput( in );
G.fill();
G.drawSolution( 3 );
}
| |