Pagini recente » Cod sursa (job #257207) | Cod sursa (job #1962210) | Cod sursa (job #2641472) | Cod sursa (job #2779008) | Cod sursa (job #2717205)
#include <fstream>
#include <queue>
using namespace std;
int dlin[6]= {-1,0,1,0};
int dcol[6]= {0,1,0,-1};
int matdr[1005][1005],mat[1005][1005],matver[1005][1005];
queue<int>lin;
queue<int>col;
int n,m,nr;
int st1,st2,dr1,dr2;
void Lee()
{
int i,j,i1,j1;
while(!lin.empty())
{
i=lin.front();
j=col.front();
for(int k=0; k<4; k++)
{
i1=i+dlin[k];
j1=j+dcol[k];
if(i1>=1&&i1<=n&&j1>=1&&j1<=m)
{
if(matdr[i1][j1]==0)
{
matdr[i1][j1]=matdr[i][j]+1;
lin.push(i1);
col.push(j1);
}
}
}
lin.pop();
col.pop();
}
}
inline void Lee1(int dist)
{
int i,j,i1,j1;
while(!lin.empty())
{
i=lin.front();
j=col.front();
for(int k=0; k<4; k++)
{
i1=i+dlin[k];
j1=j+dcol[k];
if(matver[i1][j1]!=nr&&mat[i1][j1]==0&&matdr[i1][j1]-1>=dist)
{
matver[i1][j1]=nr;
lin.push(i1);
col.push(j1);
if(i1==dr1&&j1==dr2)
{
return;
}
}
}
lin.pop();
col.pop();
}
}
int main()
{
ifstream fin("barbar.in");
ofstream fout("barbar.out");
string s;
fin>>n>>m;
for(int i=1; i<=n; i++)
{
fin>>s;
for(int j=1; j<=m; j++)
{
if(s[j-1]=='D')
{
matdr[i][j]=1;
lin.push(i);
col.push(j);
mat[i][j]=-1;
}
else if(s[j-1]=='I')
{
st1=i;
st2=j;
}
else if(s[j-1]=='O')
{
dr1=i;
dr2=j;
}
else if(s[j-1]=='*')
{
mat[i][j]=-1;
}
}
}
for(int i=0;i<=n+1;i++)
{
mat[i][0]=mat[i][m+1]=-1;
}
for(int i=0;i<=m+1;i++)
{
mat[0][i]=mat[n+1][i]=-1;
}
Lee();
int st=1,dr=1000000,mij,val=-1;
nr=1;
while(dr>=st)
{
while(!lin.empty())
{
lin.pop();
col.pop();
}
mij=(st+dr)/2;
if(matdr[st1][st2]-1>=mij)
{
lin.push(st1);
col.push(st2);
matver[st1][st2]=nr;
}
Lee1(mij);
if(matver[dr1][dr2]!=nr)
{
dr=mij-1;
}
else
{
val=mij;
st=mij+1;
}
nr++;
}
fout<<val<<'\n';
return 0;
}