Pagini recente » Cod sursa (job #2638145) | Cod sursa (job #2975003) | Cod sursa (job #1288086) | Cod sursa (job #1028670) | Cod sursa (job #2812437)
#include <iostream>
#include <fstream>
#include <queue>
using namespace std;
ifstream fin("barbar.in");
ofstream fout("barbar.out");
const int Nmax=1005;
char a[Nmax][Nmax];
bool viz[Nmax][Nmax];
int n,m,k,dist[Nmax][Nmax],sol[Nmax][Nmax];
struct celula
{
int lin,col;
};
queue<celula>q;
bool isValid(celula cell)
{
return(cell.lin>=1 &&cell.lin<=n &&
cell.col>=1 && cell.col<=m &&
a[cell.lin][cell.col]!='*' &&
viz[cell.lin][cell.col]==0 &&
dist[cell.lin][cell.col]==-1);
}
bool isValid2(celula cell,int mid)
{
return(cell.lin>=1 &&cell.lin<=n &&
cell.col>=1 && cell.col<=m &&
a[cell.lin][cell.col]!='*' &&
sol[cell.lin][cell.col]==-1 &&
dist[cell.lin][cell.col]>=mid);
}
void Lee()
{
const int dx[]= {-1,0,1,0};
const int dy[]= {0,1,0,-1};
while(!q.empty())
{
celula cell=q.front();
q.pop();
for(int dir=0; dir<4; dir++)
{
celula neighbor = {cell.lin+dx[dir],cell.col+dy[dir]};
if(isValid(neighbor))
{
dist[neighbor.lin][neighbor.col]=dist[cell.lin][cell.col] + 1;
q.push(neighbor);
}
}
}
}
void Lee2(celula cell,int mid)
{
const int dx[]= {-1,0,1,0};
const int dy[]= {0,1,0,-1};
q.push(cell);
while(!q.empty())
{
cell=q.front();
q.pop();
for(int dir=0; dir<4; dir++)
{
celula neighbor = {cell.lin+dx[dir],cell.col+dy[dir]};
if(isValid2(neighbor,mid))
{
sol[neighbor.lin][neighbor.col]=sol[cell.lin][cell.col] + 1;
q.push(neighbor);
}
}
}
}
int main()
{
celula startq,finish,start;
fin>>n>>m;
char x;
for(int i=1; i<=n; i++)
{
for(int j=1; j<=n; j++)
{
dist[i][j]=-1;
sol[i][j]=-1;
fin>>x;
a[i][j]=x;
if(x=='D')
{
startq= {i,j};
q.push(startq);
dist[i][j]=0;
}
if(x=='O')
{
finish= {i,j};
}
if(x=='I')
{
start= {i,j};
sol[i][j]=0;
}
}
}
Lee();
/*for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
fout<<dist[i][j]<<' ';
}
fout<<'\n';
}*/
int l=0,r=1000000,mid,solutie;
while(l<r)
{
mid=(l+r)/2;
if(mid<=dist[start.lin][start.col])
{
for(int i=1; i<=n; i++)
{
for(int j=1; j<=m; j++)
{
sol[i][j]=-1;
}
}
sol[start.lin][start.col]=0;
Lee2(start,mid);
if(sol[finish.lin][finish.col]==-1)
{
r=mid-1;
}
else
{
l=mid;
solutie=mid;
}
}
else
{
r=mid-1;
}
}
fout<<solutie;
return 0;
}