Pagini recente » Cod sursa (job #236602) | Cod sursa (job #2833257) | Cod sursa (job #1008637) | Cod sursa (job #714244) | Cod sursa (job #2168796)
#include <fstream>
#include <queue>
using namespace std;
ifstream f("barbar.in");
ofstream g("barbar.out");
#define oo (1 << 30)
const int NMAX = 1005;
int n, m, b[NMAX][NMAX], c[NMAX][NMAX];
int dx[] = { 1,-1,0,0 };
int dy[] = { 0,0,1,-1 };
char a[NMAX][NMAX];
int OK(int i, int j)
{
if (i<1 || i>n || j<1 || j>m)
return 0;
if (a[i][j] != '*')
return 1;
return 0;
}
int main()
{
int x1, x2, y1, y2;
queue< pair <int, int> > coada;
f >> n >> m;
for(int i=1;i<=n;i++)
for (int j = 1; j <= m; j++)
{
f >> a[i][j];
if (a[i][j] == 'D')
{
coada.push(make_pair(i, j));
b[i][j] = 0;
}
else
{
if (a[i][j] == 'I')
{
x1 = i;
y1 = j;
}
else
if (a[i][j] == 'O')
{
x2 = i;
y2 = j;
}
b[i][j] = oo;
}
}
while (!coada.empty())
{
int x = coada.front().first;
int y = coada.front().second;
coada.pop();
for (int directie = 0; directie < 4; directie++)
{
int x_urmator = x + dx[directie];
int y_urmator = y + dy[directie];
if (OK(x_urmator, y_urmator) && b[x_urmator][y_urmator] > b[x][y] + 1)
{
b[x_urmator][y_urmator] = 1 + b[x][y];
coada.push(make_pair(x_urmator, y_urmator));
}
}
}
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
c[i][j] = -1;
coada.push(make_pair(x1, y1));
c[x1][y1] = b[x1][y1];
while (!coada.empty())
{
int x = coada.front().first;
int y = coada.front().second;
coada.pop();
for (int directie = 0; directie < 4; directie++)
{
int x_urmator = x + dx[directie];
int y_urmator = y + dy[directie];
if (OK(x_urmator, y_urmator))
{
if (c[x_urmator][y_urmator] == -1)
{
c[x_urmator][y_urmator] = min(b[x_urmator][y_urmator], c[x][y]);
coada.push(make_pair(x_urmator, y_urmator));
}
else
if (c[x_urmator][y_urmator] < min(c[x][y], b[x_urmator][y_urmator]))
{
c[x_urmator][y_urmator] = min(c[x][y], b[x_urmator][y_urmator]);
coada.push(make_pair(x_urmator, y_urmator));
}
}
}
}
g << c[x2][y2];
}