Pagini recente » Cod sursa (job #1933938) | Cod sursa (job #664119) | Cod sursa (job #567881) | Cod sursa (job #2964390) | Cod sursa (job #2786215)
#include <bits/stdc++.h>
#pragma GCC optimize("O3")
using namespace std;
typedef pair<int,int> pii;
ifstream fin("barbar.in");
ofstream fout("barbar.out");
int n,m;
int diri[5]={0,0,1,-1};
int dirj[5]={-1,1,0,0};
char v[1005][1005];
int dist[1005][1005],best[1005][1005];
queue<pii> coada;
string s;
int main()
{
ios_base::sync_with_stdio(false);
fin.tie(0);
fin>>n>>m;
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
dist[i][j]=1e9;
for(int i=1;i<=n;i++)
{
fin>>s;
for(int j=1;j<=m;j++)
{
v[i][j]=s[j-1];
if(v[i][j]=='D')
{
coada.push({i,j});
dist[i][j]=0;
}
}
}
while(!coada.empty())
{
int x=coada.front().first,y=coada.front().second;
coada.pop();
for(int p=0;p<4;p++)
{
int l=x+diri[p];
int c=y+dirj[p];
if(l>0&&l<=n&&c>0&&c<=m)
if(v[l][c]!='*'&&dist[l][c]>dist[x][y]+1)
{
dist[l][c]=dist[x][y]+1;
coada.push({l,c});
}
}
}
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
if(v[i][j]=='I')
{
coada.push({i,j});
best[i][j]=dist[i][j];
}
while(!coada.empty())
{
int x=coada.front().first,y=coada.front().second;
coada.pop();
for(int p=0;p<4;p++)
{
int l=x+diri[p];
int c=y+dirj[p];
if(l>0&&l<=n&&c>0&&c<=m)
if(v[l][c]!='*'&&v[l][c]!='D'&&best[l][c]<min(best[x][y],dist[l][c]))
{
best[l][c]=min(best[x][y],dist[l][c]);
coada.push({l,c});
}
}
}
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
if(v[i][j]=='O')
{
if(best[i][j]==0)
best[i][j]=-1;
fout<<best[i][j];
}
return 0;
}