Pagini recente » Cod sursa (job #369061) | Cod sursa (job #1107815) | Cod sursa (job #613893) | Cod sursa (job #338991) | Cod sursa (job #2693763)
#include <bits/stdc++.h>
using namespace std;
ifstream f("barbar.in");
ofstream g("barbar.out");
int dl[]={-1,0,1,0};
int dc[]={0,1,0,-1};
struct pct{
int l,c;
};
queue <pct> auxq;
queue <pct> q;
const int N=1e3+10;
int mat[N][N],n,m,maxi_rez=INT_MIN,mat_rez[N][N];
pct st[N*N];
pct start,stop;
bool verif(int x,int y)
{
if(x<1 || x>n || y<1 || y>m || mat[x][y]<0)
return false;
return true;
}
void bfs()
{
while(!auxq.empty())
{
int i,j;
i=auxq.front().l;
j=auxq.front().c;
auxq.pop();
for(int k=0;k<4;k++)
{
int ix,jx;
ix=i+dl[k];
jx=j+dc[k];
if(verif(ix,jx))
{
pct aux;
aux.l=ix;
aux.c=jx;
q.push(aux);
mat[ix][jx]=1;
}
}
}
while(!q.empty())
{
int i,j,delta;
i=q.front().l;
j=q.front().c;
delta=mat[i][j]+1;
for(int k=0;k<4;k++)
{
int ix,jx;
ix=i+dl[k];
jx=j+dc[k];
if(verif(ix,jx))
{
if(delta<mat[ix][jx] && mat[ix][jx]!=0)
{
mat[ix][jx]=delta;
pct aux;
aux.l=ix;
aux.c=jx;
q.push(aux);
}
else
if(mat[ix][jx]==0)
{
mat[ix][jx]=delta;
pct aux;
aux.l=ix;
aux.c=jx;
q.push(aux);
}
}
}
q.pop();
}
}
void afisare()
{
g<<"\n\n";
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
if(mat_rez[i][j]==0)
{
g<<mat[i][j]<<" ";
}
else
{
g<<"D"<<" ";
}
}
g<<"\n";
}
g<<"\n\n";
}
void completare_rezultat(pct k)
{
pct aux;
for(int i=0;i<4;i++)
{
int ix,jx;
ix=k.l+dl[i];
jx=k.c+dc[i];
if(verif(ix,jx))
{
int rez=min(mat_rez[k.l][k.c],mat[ix][jx]);
if(mat_rez[ix][jx]==0 || mat_rez[ix][jx]<rez)
{
mat_rez[ix][jx]=rez;
aux.l=ix;
aux.c=jx;
completare_rezultat(aux);
}
}
}
}
int main()
{
f>>n>>m;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
char c;
f>>c;
if(c=='.')
{
mat[i][j]=0;
}
else
if(c=='I')
{
start.l=i;
start.c=j;
mat[i][j]=0;
}
else
if(c=='D')
{
pct aux;
aux.l=i;
aux.c=j;
mat[i][j]=-1;
auxq.push(aux);
mat_rez[i][j]=-1;
}
else
if(c=='*')
{
mat[i][j]=-1;
mat_rez[i][j]=-1;
}
else
if(c=='O')
{
stop.l=i;
stop.c=j;
mat[i][j]=0;
}
}
}
bfs();
pct aux;
mat_rez[start.l][start.c]=mat[start.l][start.c];
completare_rezultat(start);
g<<mat_rez[stop.l][stop.c];
return 0;
}