Pagini recente » Cod sursa (job #484441) | Cod sursa (job #2034038) | Cod sursa (job #2648945) | Cod sursa (job #62012) | Cod sursa (job #1025892)
#include <iostream>
#include <fstream>
#include <queue>
#include <utility>
#define INF 0x3f3f3f
#define mp make_pair
#define nmax 1005
using namespace std;
ifstream in("barbar.in");
ofstream out("barbar.out");
queue< pair<int,int> > q;
int R, C, d[nmax][nmax], p[nmax][nmax];
int ix, iy, ox, oy;
char c;
void bordeaza()
{
for ( int i=0; i<=R+1; ++i )
{
d[i][0] = d[i][C+1] = -1;
p[i][0] = p[i][C+1] = INF;
}
for ( int i=0; i<=C+1; ++i )
{
d[0][i] = d[R+1][i] = -1;
p[0][i] = p[R+1][i] = INF;
}
}
void distanteDragoni()
{
int i, j;
while ( !q.empty() )
{
i = q.front().first;
j = q.front().second;
q.pop();
if ( !d[i-1][j] )
d[i-1][j] = d[i][j] + 1, q.push( mp(i-1, j) );
if ( !d[i][j+1] )
d[i][j+1] = d[i][j] + 1, q.push( mp(i, j+1) );
if ( !d[i+1][j] )
d[i+1][j] = d[i][j] + 1, q.push( mp(i+1, j) );
if ( !d[i][j-1] )
d[i][j-1] = d[i][j] + 1, q.push( mp(i, j-1) );
}
}
void parcurgere()
{
int i, j, dist;
q.push( mp(ix, iy) );
p[ix][iy] = d[ix][iy];
while( !q.empty() )
{
i = q.front().first;
j = q.front().second;
q.pop();
dist = min ( p[i][j], d[i-1][j] );
if ( p[i-1][j] < dist )
p[i-1][j] = dist, q.push( mp(i-1, j) );
dist = min ( p[i][j], d[i][j+1] );
if ( p[i][j+1] < dist )
p[i][j+1] = dist, q.push( mp(i, j+1) );
dist = min ( p[i][j], d[i+1][j] );
if ( p[i+1][j] < dist )
p[i+1][j] = dist, q.push( mp(i+1, j) );
dist = min ( p[i][j], d[i][j-1] );
if ( p[i][j-1] < dist )
p[i][j-1] = dist, q.push( mp(i, j-1) );
}
}
int main()
{
in >> R >> C;
bordeaza();
for ( int i=1; i<=R; ++i )
for ( int j=1; j<=C; ++j )
{
in >> c;
switch(c)
{
case 'D':
p[i][j] = INF;
q.push( mp(i, j) );
break;
case '*':
d[i][j] = -1;
p[i][j] = INF;
break;
case 'I':
ix = i;
iy = j;
break;
case 'O':
ox = i;
oy = j;
break;
}
}
distanteDragoni();
parcurgere();
if ( !p[ox][oy] ) out << -1;
else out << p[ox][oy];
}