Pagini recente » Cod sursa (job #3295706) | Cod sursa (job #2943567) | Rating Sugi pula (notoast) | Cod sursa (job #334402) | Cod sursa (job #3297706)
#include <bits/stdc++.h>
#define NMAX 1002
using namespace std;
ifstream fin("barbar.in");
ofstream fout("barbar.out");
struct pos{
int y,x,d;
};
bool operator<(const pos &p1, const pos&p2)
{
return p1.d < p2.d;
}
int N,M;
int stx,sty,fix,fiy;
char a[NMAX][NMAX];
priority_queue <pos> pq;
queue <pos> q;
int ans[NMAX][NMAX];
int dist[NMAX][NMAX];
int main()
{
fin >> N >> M;
for(int i=1;i<=N;i++){
for(int j=1;j<=M;j++){
fin >> a[i][j];
if(a[i][j]=='D'){
q.push({i,j,1});
a[i][j]='.';
}else if(a[i][j]=='I'){
stx=j;
sty=i;
a[i][j]='.';
}else if(a[i][j]=='O'){
fix=j;
fiy=i;
a[i][j]='.';
}
}
}
///gasim dist pana la dragoni
while(!q.empty()){
int y=q.front().y;
int x=q.front().x;
int d=q.front().d;
q.pop();
if(y>=1 && x>=1 && y<=N && x<=M && a[y][x]=='.' && dist[y][x]==0){
dist[y][x]=d;
d++;
q.push({y+1,x,d});
q.push({y-1,x,d});
q.push({y,x+1,d});
q.push({y,x-1,d});
}
}
///acuma gasim drumu bun
pq.push({sty,stx,dist[sty][stx]-1});
while(!pq.empty()){
int y=pq.top().y;
int x=pq.top().x;
int d=pq.top().d;
pq.pop();
if(ans[fiy][fix]!=0){
fout << ans[fiy][fix];
return 0;
}
if(y>=1 && x>=1 && y<=N && x<=M && a[y][x]=='.' && ans[y][x]==0){
d=min(d,dist[y][x]-1);
ans[y][x]=d;
pq.push({y+1,x,d});
pq.push({y-1,x,d});
pq.push({y,x+1,d});
pq.push({y,x-1,d});
}
}
}