Pagini recente » Cod sursa (job #1364250) | Cod sursa (job #1898697) | Cod sursa (job #2962685) | Cod sursa (job #1604793) | Cod sursa (job #2858524)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("barbar.in");
ofstream fout("barbar.out");
const int NMAX=1005, inf=2e9;
///dist[i][j]=ditanta pana la cel mai apropiat dragon din celula (i,j)
int N, M, dist[NMAX][NMAX], dl[]={-1,0,1,0}, dc[]={0,1,0,-1};
char mat[NMAX][NMAX];
bool viz[NMAX][NMAX];
struct punct{
int x, y;
};
punct start, finish;
queue<punct> q;
bool inMatrix(int x, int y){
return x>=1 and x<=N and y>=1 and y<=M;
}
void computeDistance(){
punct p;
while(!q.empty()){
p=q.front();
q.pop();
viz[p.x][p.y]=true;
for(int k=0;k<4;k++){
if(inMatrix(p.x+dl[k],p.y+dc[k]) and viz[p.x+dl[k]][p.y+dc[k]]==false){
dist[p.x+dl[k]][p.y+dc[k]]=dist[p.x][p.y]+1;
q.push({p.x+dl[k],p.y+dc[k]});
}
}
}
}
bool verificare(int d){
if(dist[start.x][start.y]<d)
return 0;
while(!q.empty())
q.pop();
for(int i=1;i<=N;i++)
for(int j=1;j<=M;j++)
viz[i][j]=false;
q.push({start.x,start.y});
viz[start.x][start.y]=true;
punct p;
while(!q.empty()){
p=q.front();
q.pop();
if(p.x==finish.x and p.y==finish.y)
return 1;
for(int k=0;k<4;k++){
if(inMatrix(p.x+dl[k],p.y+dc[k])){
if(mat[p.x+dl[k]][p.y+dc[k]]!='*' and dist[p.x+dl[k]][p.y+dc[k]]>=d and viz[p.x+dl[k]][p.y+dc[k]]==false){
viz[p.x+dl[k]][p.y+dc[k]]=true;
q.push({p.x+dl[k],p.y+dc[k]});
}
}
}
}
return 0;
}
int main()
{
fin>>N>>M;
for(int i=1;i<=N;i++){
for(int j=1;j<=M;j++){
fin>>mat[i][j];
if(mat[i][j]=='D'){
dist[i][j]=0;
q.push({i,j});
}
if(mat[i][j]=='I'){
start.x=i;
start.y=j;
}
if(mat[i][j]=='O'){
finish.x=i;
finish.y=j;
}
}
}
computeDistance();
int st=0, dr=N+M, mij;
while(dr-st>1){
mij=(st+dr)/2;
if(verificare(mij))
st=mij;
else
dr=mij;
}
if(st==0)
fout<<-1;
else
fout<<st;
fin.close();
fout.close();
return 0;
}