Pagini recente » Cod sursa (job #2768875) | Cod sursa (job #1264788) | Cod sursa (job #407090) | Cod sursa (job #743858) | Cod sursa (job #2646395)
#include <fstream>
#include <queue>
using namespace std;
ifstream in("barbar.in");
ofstream out("barbar.out");
struct data {
short int x,y;
short int worst;
bool operator <(const data& x) const {
return worst<x.worst;
}
};
static data makedata(int x,int y, int worst) {
data rez;
rez.x=x;
rez.y=y;
rez.worst=worst;
return rez;
}
priority_queue<data> pq;
queue <data> q;
short rez;
char mat[1002][1002];
int startx,starty,endx,endy;
char dirx[4]={1,-1,0,0};
char diry[4]={0,0,1,-1};
static void findroad() {
if(pq.empty())
return;
int x=pq.top().x,y=pq.top().y,worst=pq.top().worst;
pq.pop();
mat[x][y]=-1;
if(endx==x && endy==y) {
while(!pq.empty())
pq.pop();
if(worst==1)
worst=0;
rez=worst-1;
}
else {
for(int i=0; i<4; i++) {
if(mat[x+dirx[i]][y+diry[i]]!=-1)
pq.push(makedata(x+dirx[i],y+diry[i],min(worst,(int)mat[x+dirx[i]][y+diry[i]])));
}
}
findroad();
return;
}
static void setup() {
if(q.empty())
return;
int x=q.front().x,y=q.front().y,worst=q.front().worst;
q.pop();
for(int i=0; i<4; i++) {
if(mat[x+dirx[i]][y+diry[i]]==0) {
mat[x+dirx[i]][y+diry[i]]=worst+1;
q.push(makedata(x+dirx[i],y+diry[i],worst+1));
}
}
setup();
return;
}
int main()
{
short int n,m;
char ch;
in >> n >> m;
for(int i=0; i<=n+1; i++)
mat[i][0]=mat[i][m+1]=-1;
for(int i=0; i<=m+1; i++)
mat[0][i]=mat[n+1][i]=-1;
for(int i=1; i<=n; i++) {
for(int j=1; j<=m; j++) {
in >> ch;
if(ch=='*')
mat[i][j]=-1;
else if(ch=='I') {
startx=i;
starty=j;
}
else if(ch=='O') {
endx=i;
endy=j;
}
else if(ch=='D') {
mat[i][j]=1;
q.push(makedata(i,j,1));
}
}
}
setup();
pq.push(makedata(startx,starty,mat[startx][starty]));
rez=-1;
findroad();
out << rez;
return 0;
}