Pagini recente » Cod sursa (job #1562137) | Cod sursa (job #1612591) | Cod sursa (job #199696) | Cod sursa (job #2788732) | Cod sursa (job #1591888)
#include <fstream>
#include <iostream>
#include <queue>
using namespace std;
ifstream fi("barbar.in");
ofstream fo("barbar.out");
void fill(int x, int y, int cost);
bool check(int k);
int caut();
void bordare();
void citeste();
void fazero();
bool existasol();
int dl[] = { -1, 0, 1, 0 };
int dc[] = { 0, 1, 0, -1 };
struct coada{
int lin, col;
};
queue<coada> C;
int mat[1004][1004], c[1004][1004];
int n, m, start = 1, ultim = 1;
int pl, pc, cl, cc;
int main()
{
int x, y, xx, yy, dist;
coada b;
citeste();
bordare();
if (existasol())
{
fazero();
while (!C.empty())
{
x = C.front().lin;
y = C.front().col;
for (int i = 0; i < 4; i++)
{
xx = x + dl[i];
yy = y + dc[i];
if (mat[xx][yy] == 0)
{
b.lin = xx;
b.col = yy;
C.push(b);
mat[xx][yy] = mat[x][y] + 1;
}
}
C.pop();
}
dist = caut();
fo << dist;
}
else fo << -1;
return 0;
}
void citeste()
{
int i, j;
char a;
coada b;
fi >> n >> m;
for (i = 1; i <= n; i++)
{
for (j = 1; j <= m; j++)
{
fi >> a;
if (a == '.')
mat[i][j] = 0;
if (a == 'D')
{
mat[i][j] = 0;
c[i][j] = -1;
b.lin = i;
b.col = j;
C.push(b);
}
if (a == 'I')
{
pl = i;
pc = j;
}
if (a == 'O')
{
cl = i;
cc = j;
}
if (a == '*')
{
mat[i][j] = -1;
c[i][j] = -1;
}
}
}
}
void bordare()
{
int i, j;
for (i = 0; i <= n + 1; i++)
{
mat[i][0] = -1;
mat[i][m + 1] = -1;
c[i][0] = -1;
c[i][m + 1] = -1;
}
for (j = 0; j <= m + 1; j++)
{
mat[0][j] = -1;
mat[n + 1][j] = -1;
c[0][j] = -1;
c[n + 1][j] = -1;
}
}
bool check(int k)
{
c[cl][cc] = 0;
fill(pl, pc, k);
if (c[cl][cc] >= k)
return true;
return false;
}
int caut()
{
int i = 0;
int pas = 1 << 10;
while (pas)
{
if (check(i + pas))
i += pas;
pas /= 2;
fazero();
}
return i;
}
void fill(int x, int y, int cost)
{
int i;
int xx, yy;
c[x][y] = cost;
for (i = 0; i < 4; i++)
{
xx = x + dl[i];
yy = y + dc[i];
if (mat[xx][yy] >= cost && c[xx][yy]==0)
fill(xx, yy, cost);
}
}
void fill1(int x, int y, int cost)
{
int i;
int xx, yy;
c[x][y] = cost;
for (i = 0; i < 4; i++)
{
xx = x + dl[i];
yy = y + dc[i];
if (c[xx][yy] == 0)
fill1(xx, yy, cost);
}
}
void fazero()
{
int i, j;
for (i = 1; i <= n; i++)
{
for (j = 1; j <= n; j++)
c[i][j] = 0;
}
}
bool existasol()
{
c[pl][pc] = 0;
fill1(pl, pc, 1);
if (c[cl][cc] != 0)
return true;
return false;
}