Pagini recente » Cod sursa (job #743990) | Cod sursa (job #1519698) | Cod sursa (job #1585097) | Cod sursa (job #2742830) | Cod sursa (job #2792944)
#include <bits/stdc++.h>
using namespace std;
ifstream fin ("barbar.in");
ofstream fout ("barbar.out");
const int INF = (1<<30);
const int MAXN = 1005;
int closestDragon[MAXN][MAXN], freq[MAXN][MAXN], best[MAXN][MAXN];
char mat[MAXN][MAXN]; string row;
int n, m, sol;
void debug(int test[MAXN][MAXN]){
for(int i=1; i<=n; i++, cout<<"\n")
for(int j=1; j<=m; j++, cout<<" ")
if(mat[i][j] == '*')
cout<<"*";
else
cout<<test[i][j];
}
struct End{
int ii;
int jj;
}in, out;
struct cell{
int ii;
int jj;
int dd;
}aux, nod;
int di[] = {+1, -1, 0, 0};
int dj[] = { 0, 0, +1, -1};
void bfs1(int is, int js, int paint){
queue <cell> q; aux.ii = is; aux.jj = js; aux.dd=0;
q.push(aux);
while(!q.empty()){
nod = q.front();
q.pop();
closestDragon[nod.ii][nod.jj]=nod.dd;
freq[nod.ii][nod.jj] = paint;
for(int dir=0; dir < 4; dir++){
int newi = nod.ii + di[dir];
int newj = nod.jj + dj[dir];
if(1 <= newi && newi <= n && 1 <= newj && newj <= m)
if(mat[newi][newj] != '*')
if(freq[newi][newj] != paint)
if(closestDragon[newi][newj] > closestDragon[nod.ii][nod.jj] + 1){
aux.ii = newi;
aux.jj = newj;
aux.dd = closestDragon[nod.ii][nod.jj] + 1;
q.push(aux);
}
}
}
}
void bfs2(int is, int js, int paint){
queue <cell> q;
aux.ii = is; aux.jj = js; aux.dd=closestDragon[is][js];
q.push(aux);
best[is][js] = INF;
while(!q.empty()){
nod = q.front();
q.pop();
if(nod.ii == out.ii && nod.jj == out.jj){
sol = max(sol, nod.dd);
continue;
}
for(int dir=0; dir < 4; dir++){
int newi = nod.ii + di[dir];
int newj = nod.jj + dj[dir];
if(1 <= newi && newi <= n && 1 <= newj && newj <= m)
if(mat[newi][newj] != '*')
if(best[newi][newj] < nod.dd){
best[newi][newj] = nod.dd;
aux.ii = newi; aux.jj = newj; aux.dd = min(nod.dd, closestDragon[newi][newj]);
q.push(aux);
}
}
}
}
int main (){
fin>>n>>m;
for(int i=1; i<=n; i++){
fin>>row;
for(int j=0; j<m; j++){
mat[i][j+1] = row[j];
closestDragon[i][j+1] = INF;
best[i][j+1] = -1;
}
}
int color;
for(int i=1; i<=n; i++)
for(int j=1; j<=m; j++){
if(mat[i][j] == 'D')
bfs1(i, j, ++color);
if(mat[i][j] == 'I'){
in.ii=i;
in.jj=j;
}
if(mat[i][j] == 'O'){
out.ii=i;
out.jj=j;
}
}
//debug(closestDragon);
sol=0;
bfs2(in.ii, in.jj, ++color);
fout<<sol;
return 0;
}