Pagini recente » Cod sursa (job #369712) | Cod sursa (job #198482) | Cod sursa (job #204823) | Cod sursa (job #233051) | Cod sursa (job #2800958)
#include <fstream>
#include <queue>
using namespace std;
const int N = 1000;
char a [ N ][ N ];
int dist [ N ][ N ], traseu [ N ][ N ];
int d_lin[4] = { -1, 0, 1, 0 };
int d_col[4] = { 0, 1, 0, -1 };
queue < pair <int, int> > lee;
int main ( ) {
ifstream fin ( "barbar.in" );
ofstream fout ( "barbar.out" );
int n, m, i, j, lin0 = 0, col0 = 0, linF = 0, colF = 0, max = 0, ok = 0;
fin >> n >> m;
for ( i = 0; i < n; i++ ){
for ( j = 0; j < m; j++ ){
fin >> a [ i ][ j ];
if ( a[ i ][ j ] == 'D' ){
lee.push ( { i, j } );
dist [ i ][ j ] = 1;
}
if ( a[ i ][ j ] == '*' ){
dist [ i ][ j ] = -1;
}
}
}
while ( lee.size () > 0 ) {
pair <int, int> c = lee.front();
lee.pop();
if ( c.first >= 0 && c.first < n && c.second >= 0 && c.second < m && dist[ c.first ][ c.second ] != -1 ){
for ( int i = 0; i < 4; i++ ) {
int lin1 = c.first + d_lin [ i ];
int col1 = c.second + d_col [ i ];
if ( lin1 >= 0 && lin1 < n && col1 >= 0 && col1 < m && dist [ lin1 ][ col1 ] == 0 ) {
dist [ lin1 ][ col1 ] = dist[ c.first ][ c.second ] + 1;
lee.push ( { lin1, col1 } );
}
}
}
}
for ( i = 0; i < n; i++ ){
for ( j = 0; j < m; j++ ){
if ( a [ i ][ j ] == 'I' ){
lin0 = i;
col0 = j;
}
if ( a [ i ][ j ] == 'O' ){
linF = i;
colF = j;
}
dist [ i ][ j ] -- ;
if ( dist [ i ][ j ] > max )
max = dist [ i ][ j ];
}
}
int st = 0, dr = max + 1, mij;
while ( dr - st > 1 ) {
mij = ( dr + st ) / 2;
lee.push ( { lin0, col0 } );
traseu[ lin0 ][ col0 ] = 1;
while ( traseu [ linF ][ colF ] == 0 && lee.size ( ) > 0 ) {
pair < int, int > c = lee.front ( );
lee.pop ( );
for ( int i = 0; i < 4; i++ ) {
int lin1 = c.first + d_lin [ i ];
int col1 = c.second + d_col [ i ];
if ( lin1 >= 0 && lin1 < n && col1 >= 0 && col1 < m && traseu [ lin1 ][ col1 ] == 0 && dist [ lin1 ][ col1 ] >= mij ) {
traseu [ lin1 ][ col1 ] = 1;
lee.push ( { lin1, col1 } );
}
}
}
if ( traseu [ linF ][ colF ] == 1 ){
st = mij;
ok = 1;
}
else
dr = mij;
for ( i = 0; i < n; i++ )
for ( j = 0; j < m; j++ )
traseu [ i ][ j ] = 0;
while ( lee.size ( ) > 0 )
lee.pop ( );
}
if ( ok == 1 )
fout << st;
else
fout << "-1";
return 0;
}