Pagini recente » Cod sursa (job #2111348) | Cod sursa (job #592059) | Cod sursa (job #730241) | Cod sursa (job #978257) | Cod sursa (job #1947272)
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
struct point
{
int x, y;
};
queue <point> q;
char a[1005][1005], stx, sty;
int d[1005][1005], finx, finy;
bool viz[1005][1005];
int dx[] = {0, -1, 0, 1, 0};
int dy[] = {0, 0, 1, 0, -1};
bool bfs(int x)
{
point aux, nou;
memset(viz, 0, sizeof(viz));
while (!q.empty())
q.pop();
aux.x = stx; aux.y = sty;
viz[stx][sty] = 1;
q.push(aux);
while (!q.empty())
{
aux = q.front();
if (aux.x == finx && aux.y == finy)
return 1;
for (int i = 1; i <= 4; ++i)
{
nou.x = aux.x + dx[i];
nou.y = aux.y + dy[i];
if (d[nou.x][nou.y] >= x && viz[nou.x][nou.y] == 0)
{
viz[nou.x][nou.y] = 1;
q.push(nou);
}
}
q.pop();
}
return 0;
}
int main()
{
freopen("barbar.in", "r", stdin);
freopen("barbar.out", "w", stdout);
int n, m, st, dr, last, med;
point aux, nou;
scanf("%d %d\n", &n, &m);
for (int i = 1; i <= n; ++i)
gets(a[i] + 1);
memset(d, -1, sizeof(d));
for (int i = 1; i <= n; ++i)
for (int j = 1; j <= m; ++j)
if (a[i][j] == 'D')
{
aux.x = i;
aux.y = j;
d[i][j] = 0;
q.push(aux);
}
else if (a[i][j] == 'I')
stx = i, sty = j;
else if (a[i][j] == 'O')
finx = i, finy = j;
while(!q.empty())
{
aux = q.front();
for (int i = 1; i <= 4; ++i)
{
nou.x = aux.x + dx[i];
nou.y = aux.y + dy[i];
if (a[nou.x][nou.y] != '*' && a[nou.x][nou.y] != 0 && d[nou.x][nou.y] == -1)
{
d[nou.x][nou.y] = d[aux.x][aux.y] + 1;
q.push(nou);
}
}
q.pop();
}
st = last = 0; dr = d[stx][sty];
while (st <= dr)
{
med = (st + dr) / 2;
if (bfs(med))
{
last = med;
st = med + 1;
}
else
dr = med - 1;
}
printf("%d\n", last);
return 0;
}