Pagini recente » Cod sursa (job #3190385) | Cod sursa (job #452844) | Cod sursa (job #2950718) | Cod sursa (job #158033) | Cod sursa (job #3266508)
#include <bits/stdc++.h>
using namespace std;
ifstream f("barbar.in");
ofstream g("barbar.out");
const int NMAX=1000;
const int INF=1e9;
char mat[NMAX+1][NMAX+1];
int dist[NMAX+1][NMAX+1];
int R,C;
int sx,sy,fx,fy;
int dx[]={0,0,-1,1};
int dy[]={-1,1,0,0};
bool verifcoord(int a,int b)
{
if(a>=1&&a<=R&&b>=1&&b<=C)
return true;
return false;
}
bool verif(int d)
{
queue<pair<int, int>> q;
bool visited[NMAX+1][NMAX+1]={false};
if(dist[sx][sy]<d)
return false;
q.push({sx, sy});
visited[sx][sy]=true;
while(!q.empty())
{
int x=q.front().first;
int y=q.front().second;
q.pop();
if(x==fx&&y==fy)
return true;
for(int k=0;k<4;k++)
{
int nx=x+dx[k];
int ny=y+dy[k];
if(verifcoord(nx,ny)&&!visited[nx][ny]&&mat[nx][ny]!='*'&&dist[nx][ny]>=d)
{
visited[nx][ny]=true;
q.push({nx,ny});
}
}
}
return false;
}
int main()
{
f>>R>>C;
for(int i=1;i<=R;i++)
{
for(int j=1;j<=C;j++)
{
f>>mat[i][j];
if(mat[i][j]=='I')
{
sx=i;
sy=j;
}
else if(mat[i][j]=='O')
{
fx=i;
fy=j;
}
}
}
queue< pair<int, int> > q;
for(int i=1;i<=R;i++)
{
for(int j=1;j<=C;j++)
{
if(mat[i][j]=='D')
{
dist[i][j]=0;
q.push({i, j});
}
else
{
dist[i][j]=INF;
}
}
}
while(!q.empty())
{
int x=q.front().first;
int y=q.front().second;
q.pop();
for(int k=0;k<4;k++)
{
int nx=x+dx[k];
int ny=y+dy[k];
if(verifcoord(nx,ny)&&mat[nx][ny]!='*'&&dist[nx][ny]>dist[x][y]+1)
{
dist[nx][ny]=dist[x][y]+1;
q.push({nx,ny});
}
}
}
int st=0,dr=R*C,sol=-1;
while(st<=dr)
{
int mid=(st+dr)/2;
if (verif(mid))
{
sol=mid;
st=mid+1;
}
else
{
dr=mid-1;
}
}
g<<sol;
return 0;
}