Pagini recente » Cod sursa (job #2424616) | Cod sursa (job #1633921) | Cod sursa (job #2453047) | Cod sursa (job #770659) | Cod sursa (job #2292346)
#include <iostream>
#include <fstream>
#include <queue>
#include <limits.h>
#include <cstring>
std::ifstream in("barbar.in");
std::ofstream out("barbar.out");
struct poz{
int x,y,cost;
bool operator <(poz aux)const{
return cost<aux.cost;
}
};
int n,m,x1,x2,y1,y2,viz[1001][1001],viz2[1001][1001];
int dx[]={-1,0,1,0};
int dy[]={0,1,0,-1};
char mat[1001][1001];
std::priority_queue<poz>q;
bool check(int g){
for(int i=1;i<=n;i++)
memset(viz2[i],0,sizeof(viz2[i]));
if(viz[x1][y1]<g)
return 0;
q.push({x1,y1,0});
while(!q.empty()){
poz p=q.top();
viz2[p.x][p.y]=1;
q.pop();
for(int i=0;i<4;i++){
poz aux={p.x+dx[i],p.y+dy[i]};
if(aux.x>=1 && aux.y>=1 && aux.x<=n && aux.y<=m && viz[aux.x][aux.y]>=g && !viz2[aux.x][aux.y] && mat[aux.x][aux.y]!='*'){
viz2[aux.x][aux.y]=1,q.push(aux);
if(aux.x==x2 && aux.y==y2){
while(!q.empty())
q.pop();
return 1;
}
}
}
}
return 0;
}
int bs(){
int p2=1<<20,r=0;
while(p2){
if(check(p2+r))
r+=p2;
p2/=2;
}
return r;
}
int main()
{
in>>n>>m;
for(int i=1;i<=n;i++){
in>>mat[i]+1;
for(int j=1;j<=m;j++){
viz[i][j]=INT_MAX;
if(mat[i][j]=='D')
q.push({i,j,0}),viz[i][j]=0;
else
if(mat[i][j]=='I')
x1=i,y1=j;
else
if(mat[i][j]=='O')
x2=i,y2=j;
}
}
while(!q.empty()){
poz p=q.top();
q.pop();
for(int i=0;i<4;i++){
poz aux={p.x+dx[i],p.y+dy[i],p.cost+1};
if(aux.x>=1 && aux.y>=1 && aux.x<=n && aux.y<=m)
if(viz[aux.x][aux.y]>aux.cost)
viz[aux.x][aux.y]=aux.cost,q.push(aux);
}
}
out<<bs();
return 0;
}