Pagini recente » Cod sursa (job #2070563) | Cod sursa (job #2086818) | Cod sursa (job #2589400) | Cod sursa (job #3039319) | Cod sursa (job #2380721)
#include <bits/stdc++.h>
#define f first
#define s second
using namespace std ;
const short NR = 1002 ;
ifstream in ("barbar.in") ;
ofstream out ("barbar.out") ;
queue < pair < short , short > > q ;
short n , m , bi , bj , ei , ej ;
short di [ 4 ] = { -1 , 0 , 1 , 0 } ;
short dj [ 4 ] = { 0 , 1 , 0 , -1 } ;
struct element {
int tip , val = -1 ;
}a [ NR ][ NR ];
bool ok ( const short i , const short j ) {
return i && j && i <= n && j <= m ;
}
void bfs () {
short d , newi , newj ;
while ( !q.empty() ) {
pair < short , short > nod = q.front() ;
q.pop() ;
for ( d = 0 ; d < 4 ; ++ d ) {
newi = nod.f + di [ d ] ;
newj = nod.s + dj [ d ] ;
if ( ok ( newi , newj ) && a [ newi ][ newj ].tip == 1 && ( a [ newi ][ newj ].val == -1 || ( a [ newi ][ newj ].val > a [ nod.f ][ nod.s ].val + 1 ) ) ) {
a [ newi ][ newj ].val = a [ nod.f ][ nod.s ].val + 1 ;
q.push ( { newi , newj } ) ;
}
}
}
}
bool test ( short k )
{
if ( k > a [ bi ][ bj ].val ) return 0 ;
short d , newi , newj ;
bool viz [ NR ][ NR ] = {0} ;
q.push( { bi , bj } ) ;
viz [ bi ][ bj ] = 1 ;
while ( !q.empty() ) {
pair < short , short > nod = q.front() ;
if ( nod.f == ei && nod.s == ej ) {
while ( !q.empty() ) q.pop() ;
return 1 ;
}
q.pop() ;
for ( d = 0 ; d < 4 ; ++ d ) {
newi = nod.f + di [ d ] ;
newj = nod.s + dj [ d ] ;
if ( ok ( newi , newj ) && a [ newi ][ newj ].tip == 1 && a [ newi ][ newj ].val != -1 && a [ newi ][ newj ].val >= k && !viz [ newi ][ newj ] ) {
viz [ newi ][ newj ] = 1 ;
q.push ( { newi , newj } ) ;
}
}
}
return 0 ;
}
short bs ()
{
short st = 1 , dr = 2000 , sol = -1 , mid ;
while ( st <= dr ) {
mid = ( st + dr ) >> 1 ;
if ( test( mid ) ) {
sol = mid ;
st = mid + 1 ;
}
else dr = mid - 1 ;
}
return sol ;
}
int main () {
short i , j ;
in >> n >> m ;
for ( i = 1 ; i <= n ; ++ i )
for ( j = 1 ; j <= m ; ++ j ) {
char c ;
in >> c ;
if ( c == '*' ) a [ i ][ j ].tip = 0 ;
if ( c == '.' ) a [ i ][ j ].tip = 1 ;
if ( c == 'D' ) a [ i ][ j ].tip = 2 , q.push ( { i , j } ) , a [ i ][ j ].val = 0 ;
if ( c == 'I' ) bi = i , bj = j , a [ i ][ j ].tip = 1 ;
if ( c == 'O' ) ei = i , ej = j , a [ i ][ j ].tip = 1 ;
}
bfs() ;
out << bs() ;
}