Pagini recente » Cod sursa (job #2163137) | Cod sursa (job #2347823) | Cod sursa (job #2954683) | Cod sursa (job #549498) | Cod sursa (job #567668)
Cod sursa(job #567668)
#include<fstream>
#include<iomanip>
#include<queue>
#define nnn 1010
#define inf INT_MAX
using namespace std;
const int dx[]={0,0,-1,1};
const int dy[]={-1,1,0,0};
int m,n,sx,sy,fx,fy;
int d[nnn],a[nnn][nnn],v[nnn][nnn];
struct punct {int x,y;};
queue<punct> q;
punct p,o;
// 0 - liber
// -2 - dragon
//
ofstream out("barbar.out");
void afs()
{
int i,j;
for (i=1;i<=n;i++)
{
for (j=1;j<=m;j++)
out<<setfill(' ')<<setw(2)<<a[i][j]<<" ";
out<<'\n';
}
out<<"\n\n\n";
for (i=1;i<=n;i++)
{
for (j=1;j<=m;j++)
out<<setfill(' ')<<setw(2)<<v[i][j]<<" ";
out<<'\n';
}
out<<"\n\n\n";
}
void citire()
{
int i,j;
char c;
ifstream in("barbar.in");
in>>n>>m;
in.get();
for (i=1;i<=n;i++)
{
for (j=1;j<=m;j++)
{
in.get(c);
if (c=='.')
v[i][j]=0;
else if (c=='D')
{
v[i][j]=-2;
a[i][j]=-2;
p.x=i;
p.y=j;
q.push(p);
}
else if (c=='*')
{
v[i][j]=-1;
a[i][j]=-1;
}
else if (c=='I')
{
sx=i;
sy=j;
}
else if (c=='O')
{
fx=i;
fy=j;
}
}
in.get();
}
}
int val(int a)
{
if (a==-2)
return 0;
return a;
}
void dist_dragoni()
{
int x,y,i,xx,yy;
while (!q.empty())
{
p=q.front();
q.pop();
x=p.x;
y=p.y;
for (i=0;i<4;i++)
{
xx=x+dx[i];
yy=y+dy[i];
if ( (!a[xx][yy]||a[xx][yy]>val(a[x][y])+1)&&xx>0&&yy>0&&xx<=n&&y<=m&&v[xx][yy]!=-1)
{
a[xx][yy]=val(a[x][y])+1;
o.x=xx;
o.y=yy;
q.push(o);
}
}
}
/* for (i=1;i<=n;i++)
for (j=1;j<=n;j++)
if (v[i][j]==-2)
v[i][j]=0;*/
}
void drum()
{
int i,x,y,xx,yy;
while (!q.empty())
q.pop();
p.x=sx;
p.y=sy;
q.push(p);
v[sx][sy]=a[sx][sy];
while (!q.empty())
{
p=q.front();
q.pop();
x=p.x;
y=p.y;
for (i=0;i<4;i++)
{
xx=x+dx[i];
yy=y+dy[i];
if (xx>0&&yy>0&&xx<=n&&y<=m&&v[xx][yy]!=-1)
{
if (!v[xx][yy])
{
v[xx][yy]=min(val(a[xx][yy]),val(v[x][y]));
o.x=xx;
o.y=yy;
q.push(o);
}
else if (val(v[xx][yy])<val(a[xx][yy])&&val(v[x][y])>val(v[xx][yy]))
{
v[xx][yy]=min(v[x][y],a[xx][yy]);
o.x=xx;
o.y=yy;
q.push(o);
}
}
}
}
}
int main()
{
citire();
dist_dragoni();
drum();
//afs();
if (v[fx][fy]==-2)
out<<0<<'\n';
else if (v[fx][fy]==0)
out<<-1;
else
out<<val(v[fx][fy])<<'\n';
}