Pagini recente » Cod sursa (job #710516) | Cod sursa (job #1470099) | Cod sursa (job #320925) | Cod sursa (job #2054419) | Cod sursa (job #1947310)
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int INF = 10000000;
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);
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, d[i][j] = INF;
else if (a[i][j] == 'O')
finx = i, finy = j, d[i][j] = INF;
else if (a[i][j] == '.')
d[i][j] = INF;
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] == INF)
{
d[nou.x][nou.y] = d[aux.x][aux.y] + 1;
q.push(nou);
}
}
q.pop();
}
/*for (int i = 1; i <= n; ++i){
for (int j = 1; j <= m; ++j)
printf("%2d ", d[i][j]);
printf("\n");}*/
st = 0; last = -1; 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;
}