Pagini recente » Cod sursa (job #1930938) | Cod sursa (job #768531) | Cod sursa (job #261699) | Cod sursa (job #2470698) | Cod sursa (job #2711047)
#include <bits/stdc++.h>
#define nmax 1002
using namespace std;
ifstream f("barbar.in");
ofstream g("barbar.out");
int n,m,dp[nmax][nmax];
int vect[4]={0,1,0,-1};
int vect2[4]={1,0,-1,0};
char mat[nmax][nmax];
bool marker[nmax][nmax],solutie;
pair <int ,int > x,y,dragon;
struct ceva
{
bool operator()(pair<int ,int >a, pair<int ,int >b)
{
return dp[a.first][a.second]<dp[b.first][b.second];
}
};
priority_queue <pair<int ,int >,vector <pair<int ,int > >,ceva> q;
void solve(int i,int j)
{
q.push({i,j});
while(!q.empty())
{
i=q.top().first;
j=q.top().second;
q.pop();
if(i==y.first && j==y.second)
{
g<<dp[i][j];
solutie=true;
return ;
}
for(int d=0; d<4; d++)
{
int val=i+vect[d],val2=j+vect2[d];
if(mat[val][val2]=='.')
{
dp[val][val2]=min(dp[val][val2],dp[i][j]);
if(!marker[val][val2])
{
q.push({val,val2});
marker[val][val2]=true;
}
}
}
}
}
int main()
{
f>>n>>m;
for(int i=1; i<=n; i++)
{
for(int j=1; j<=m; j++)
{
f>>mat[i][j];
if(mat[i][j]=='D')dragon={i,j};
else if(mat[i][j]=='I')
{
x={i,j};
mat[i][j]='.';
}
else if(mat[i][j]=='O')
{
y={i,j};
mat[i][j]='.';
}
dp[i][j]=nmax;
}
}
queue < pair <int ,int > > q2;
q2.push({dragon.first,dragon.second});
dp[dragon.first][dragon.second]=0;
while(!q2.empty())
{
int i=q2.front().first;
int j=q2.front().second;
q2.pop();
marker[i][j]=false;
for(int d=0; d<4; d++)
{
int val=i+vect[d],val2=j+vect2[d];
if(mat[val][val2]=='D' && dp[val][val2]!=0)
{
dp[val][val2]=0;
if(!marker[val][val2])
{
q2.push({val,val2});
marker[val][val2]=true;
}
}
else if(dp[i][j]+1<dp[val][val2] && mat[val][val2]=='.')
{
dp[val][val2]=dp[i][j]+1;
if(!marker[val][val2])
{
q2.push({val,val2});
marker[val][val2]=true;
}
}
}
}
solve(x.first,x.second);
if(!solutie)g<<-1;
return 0;
}