Pagini recente » Cod sursa (job #2385395) | Cod sursa (job #2883616) | Cod sursa (job #789165) | Cod sursa (job #2191959) | Cod sursa (job #2296062)
#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
char mat[1005][1005], viz[1500005];
int dist[1500005];
queue <int> q[500005], dragonasi, qc;
int main()
{
freopen("barbar.in", "r", stdin);
freopen("barbar.out", "w", stdout);
int r, col, i, j, start, finish, curent;
scanf("%d%d\n", &r, &col);
for(i = 1; i <= r; ++ i)
scanf("%s", &mat[i]);
for(i = 1; i <= r; ++ i)
for(j = 1; j <= col; ++ j)
{
if(mat[i][j] == 'D')
{
dragonasi.push(i * 1001 + j);
viz[i * 1001 + j] = 1;
}
if(mat[i][j] == 'I')
start = i * 1001 + j;
if(mat[i][j] == 'O')
finish = i * 1001 + j;
}
for(i = 0; i <= r + 1; ++ i)
mat[i][0] = mat[i][col + 1] = '*';
for(i = 0; i <= col + 1; ++ i)
mat[0][i] = mat[r + 1][i] = '*';
while(!(dragonasi.empty()))
{
curent = dragonasi.front();
if(viz[curent + 1001] == 0 && mat[curent / 1001 + 1][curent % 1001] != '*')
{
dist[curent + 1001] = dist[curent] + 1;
dragonasi.push(curent + 1001);
viz[curent + 1001] = 1;
}
if(viz[curent - 1001] == 0 && mat[curent / 1001 - 1][curent % 1001] != '*')
{
dist[curent - 1001] = dist[curent] + 1;
dragonasi.push(curent - 1001);
viz[curent - 1001] = 1;
}
if(viz[curent + 1] == 0 && mat[curent / 1001][curent % 1001 + 1] != '*')
{
dist[curent + 1] = dist[curent] + 1;
dragonasi.push(curent + 1);
viz[curent + 1] = 1;
}
if(viz[curent - 1] == 0 && mat[curent / 1001][curent % 1001 - 1] != '*')
{
dist[curent - 1] = dist[curent] + 1;
dragonasi.push(curent - 1);
viz[curent - 1] = 1;
}
dragonasi.pop();
}
for(i = 1; i <= 1002 * 1000; ++ i)
viz[i] = 0;
i = dist[start];
q[i].push(start);
while(viz[finish] == 0 && i >= 1)
{
while(!q[i].empty())
{
curent = q[i].front();
viz[curent] = 1;
q[i].pop();
qc.push(curent);
}
while(!qc.empty())
{
curent = qc.front();
if(viz[curent + 1001] == 0 && mat[curent / 1001 + 1][curent % 1001] != '*')
{
if(dist[curent + 1001] >= i)
qc.push(curent + 1001);
else
q[dist[curent + 1001]].push(curent + 1001);
viz[curent + 1001] = 1;
}
if(viz[curent - 1001] == 0 && mat[curent / 1001 - 1][curent % 1001] != '*')
{
if(dist[curent - 1001] >= i)
qc.push(curent - 1001);
else
q[dist[curent - 1001]].push(curent - 1001);
viz[curent - 1001] = 1;
}
if(viz[curent + 1] == 0 && mat[curent / 1001][curent % 1001 + 1] != '*')
{
if(dist[curent + 1] >= i)
qc.push(curent + 1);
else
q[dist[curent + 1]].push(curent + 1);
viz[curent + 1] = 1;
}
if(viz[curent - 1] == 0 && mat[curent / 1001][curent % 1001 - 1] != '*')
{
if(dist[curent - 1] >= i)
qc.push(curent - 1);
else
q[dist[curent - 1]].push(curent - 1);
viz[curent - 1] = 1;
}
qc.pop();
}
-- i;
}
++ i;
if(i > dist[finish])
i = dist[finish];
printf("%d", i);
return 0;
}