Pagini recente » Cod sursa (job #2713087) | Cod sursa (job #2846478) | Cod sursa (job #2974596) | Cod sursa (job #2677293) | Cod sursa (job #2557509)
#include <bits/stdc++.h>
using namespace std;
/***********************************************/
const int nmax=2000;
int r,c,xi,xf,yi,yf;
char ch;
int val[nmax][nmax],d[nmax][nmax],a[nmax][nmax];
int xDir[]= {0,1,0,-1};
int yDir[]= {-1,0,1,0};
int rasp=INT_MAX;
queue <pair<int, int> > q;
/***********************************************/
ifstream f("barbar.in");
ofstream g("barbar.out");
/***********************************************/
///------------------------------------------------------------
inline void readInput()
{
f>>r>>c;
for(int i=1; i<=r; i++)
{
for(int j=1; j<=c; j++)
{
f>>ch;
if(ch=='*') a[i][j]=-1;
if(ch=='I')
{
xi=i;
yi=j;
}
else if(ch=='O')
{
xf=i;
yf=j;
}
else if(ch=='D') q.push({i,j});
}
}
}
///------------------------------------------------------------
bool IsOnMatrix(int x, int y)
{
if(x<1 || y<1 || x>r || y>c) return 0;
if(a[x][y]==-1) return 0;
return 1;
}
///------------------------------------------------------------
void LeeDragoni()
{
while(!q.empty())
{
int xx=q.front().first;
int yy=q.front().second;
q.pop();
for(int i=0; i<4; i++)
{
int lin= xx+xDir[i];
int col=yy+yDir[i];
if(IsOnMatrix(lin,col)&& (val[lin][col]>val[xx][yy]+1 || val[lin][col]==0))
{
val[lin][col]=val[xx][yy]+1;
q.push({lin,col});
}
}
}
}
///---------------------------------------------------------------
int verif(int dist)
{
while(!q.empty())
q.pop();
for(int i=1; i<=r; i++)
for(int j=1; j<=c; j++)
d[i][j] = 0;
d[xi][yi] = 1;
if(val[xi][yi]>=dist) q.push(make_pair(xi, yi));
else return 0;
while(!q.empty())
{
int ipos = q.front().first;
int jpos = q.front().second;
q.pop();
for(int i=0; i<4; i++)
{
int lin = ipos + xDir[i];
int col = jpos + yDir[i];
if(IsOnMatrix(lin,col) && val[lin][col]>=dist && (d[lin][col]>d[ipos][jpos]+1 || d[lin][col] == 0))
{
if(lin == xf && col == yf) return 1;
d[lin][col] = d[ipos][jpos] + 1;
q.push(make_pair(lin,col));
}
}
}
return 0;
}
///------------------------------------------------------------
void CautareBinara(int st, int dr)
{
while(st<=dr)
{
int mij=(st+dr)/2;
if(verif(mij)==1)
{
rasp=mij;
st=mij+1;
}
else dr=mij-1;
}
}
///------------------------------------------------------------
inline void Solution()
{
CautareBinara(0,r*c);
if(rasp==INT_MAX) g<<"-1";
else g<<rasp;
}
///------------------------------------------------------------
int main()
{
readInput();
LeeDragoni();
Solution();
return 0;
}