Pagini recente » Cod sursa (job #800234) | Cod sursa (job #2520364) | Cod sursa (job #1562823) | Cod sursa (job #3319335) | Cod sursa (job #3346042)
#include <fstream>
#include <iostream>
#include <queue>
using namespace std;
ifstream fin("barbar.in");
ofstream fout("barbar.out");
int n, m, dist[1002][1002], copie[1002][1002];
char a[1002][1002];
struct pereche{
int x;
int y;
};
int func( int i, int j){
if(i<=n && i>=1 && j<=m && j>=1){
return 1;
}
return 0;
}
void Lee( ){
queue <pereche> q;
for(int i=1; i<=n; i++){
for(int j=1; j<=m ; j++){
if(a[i][j]=='D'){
q.push({i, j});
dist[i][j]=0;
}
}
}
while(q.empty()==0){
int i=q.front().x;
int j=q.front().y;
q.pop();
if(func(i-1, j)==1 && a[i-1][j]!='*' && dist[i-1][j]> 1+ dist[i][j] ){
dist[i-1][j]=1+dist[i][j];
q.push({i-1, j});
}
if(func(i+1, j)==1 && a[i+1][j]!='*' && dist[i+1][j]> 1+ dist[i][j] ){
dist[i+1][j]=1+dist[i][j];
q.push({i+1, j});
}
if(func(i, j-1)==1 && a[i][j-1]!='*' && dist[i][j-1]> 1+ dist[i][j] ){
dist[i][j-1]=1+dist[i][j];
q.push({i, j-1});
}
if(func(i, j+1)==1 && a[i][j+1]!='*' && dist[i][j+1]> 1+ dist[i][j] ){
dist[i][j+1]=1+dist[i][j];
q.push({i, j+1});
}
}
}
void Fill( int i, int j, int z){
if(func(i, j)==1 && a[i][j]!='*' && dist[i][j]>=z){
dist[i][j]=-1;
Fill(i, j+1,z);
Fill(i, j-1, z);
Fill(i+1, j,z);
Fill(i-1, j,z);
}
}
int main()
{ int xo, yo, xi, yi;
fin >> n >> m;
for(int i=1; i<=n; i++){
for(int j=1; j<=m; j++){
fin >> a[i][j];
dist[i][j]=2e9;
if(a[i][j]=='I'){
xi=i;
yi=j;
}
else if(a[i][j]=='O'){
xo=i;
yo=j;
}
}
}
Lee();
for(int i=1; i<=n; i++){
for(int j=1; j<=m; j++){
copie[i][j]=dist[i][j];
}
}
int st=1, dr=1000001, mij, sol=-1;
while(st<=dr){
mij=(st+dr)/2;
Fill(xi, yi, mij);
if(dist[xo][yo]==-1){
sol=mij;
st=mij+1;
}
else{
dr=mij-1;
}
for(int i=1; i<=n; i++){
for(int j=1; j<=m; j++){
dist[i][j]=copie[i][j];
}
}
}
fout << sol;
return 0;
}