Pagini recente » Cod sursa (job #3138900) | Cod sursa (job #2828464) | Cod sursa (job #2926845) | Cod sursa (job #1210188) | Cod sursa (job #2007567)
#include <fstream>
#include <queue>
using namespace std;
ofstream fout ("barbar.out");
ifstream fin ("barbar.in");
int n,m,i,j,ln,col,rsp,cs,cd,mij;
queue < pair < int , int > > q;
pair < int , int > aux,poz1,poz2;
char s[1024];
int v[1005][1005],dist[1005][1005],ajuns[1005][1005];
int dx[] = { 0 , 0 , 1 , -1 };
int dy[] = { 1 , -1 , 0 , 0 };
bool lee( int nr );
int main()
{
fin>>n>>m;
for( i = 1 ; i <= n ; i++ )
{
fin.get();
fin.get( s , 1024 );
for( j = 0 ; j < m ; j++ )
{
if( s[ j ] == '*' )
v[ i ][ j + 1 ] = -1;
if( s[ j ] == 'D' )
{
v[ i ][ j + 1 ] = -1;
q.push( { i , j + 1 } );
}
if( s[ j ] == 'I' )
poz1 = { i , j + 1 };
if( s[ j ] == 'O' )
poz2 = { i , j + 1 };
}
}
while( q.size() )
{
aux = q.front();
q.pop();
for( i = 0 ; i < 4 ; i++ )
{
ln = aux.first + dx[ i ];
col = aux.second + dy[ i ];
if( ln < 1 || col < 1 || ln > n || col > m )
continue;
if( v[ ln ][ col ] == 0 && dist[ ln ][ col ] == 0 )
{
dist[ ln ][ col ] = dist[ aux.first ][ aux.second ] + 1;
q.push( { ln , col } );
}
}
}
cs = 1;
cd = 1e3;
rsp = -1;
while( cs <= cd )
{
mij = ( cs + cd ) >> 1;
if( lee( mij ) )
cs = mij + 1;
else
cd = mij - 1;
}
fout<<rsp;
}
bool lee( int nr )
{
if( nr > dist[ poz1.first ][ poz1.second ] )
return 0;
for( i = 1 ; i <= n ; i++ )
for( j = 1 ; j <= m ; j++ )
ajuns[ i ][ j ] = 0;
q.push( poz1 );
ajuns[ poz1.first ][ poz1.second ] = 1;
while( q.size() )
{
aux = q.front();
q.pop();
for( i = 0 ; i < 4 ; i++ )
{
ln = aux.first + dx[ i ];
col = aux.second + dy[ i ];
if( ln < 1 || col < 1 || ln > n || col > m )
continue;
if( v[ ln ][ col ] == 0 && dist[ ln ][ col ] >= nr && ajuns[ ln ][ col ] == 0 )
{
ajuns[ ln ][ col ] = 1;
q.push( { ln , col } );
}
}
}
if( ajuns[ poz2.first ][ poz2.second ] == 1 )
{
rsp = nr;
return 1;
}
return 0;
}