Pagini recente » Cod sursa (job #1775792) | Cod sursa (job #1921845) | Cod sursa (job #617060) | Cod sursa (job #2081792) | Cod sursa (job #2592445)
#include <cstdio>
#include <vector>
#include <queue>
#include <string>
#include <iostream>
using namespace std;
const int NMAX = 1000;
const int MMAX = 1000;
const int INF = 2.e9;
int di[]= {-1 , 0 , 1 , 0};
int dj[]= {0 , 1 , 0 , -1};
struct dragoni
{
int x , y , z;
};
dragoni temp1 , temp2;
bool operator<(const dragoni& a , const dragoni& b)
{
return a.z > b.z;
}
struct coordonate
{
int x , y;
};
coordonate temp3 , temp4;
int drg[NMAX + 5][MMAX + 5] , d[NMAX + 5][MMAX + 5] , n , m;
bool a[NMAX + 5][MMAX + 5];
string s;
int valid(int x , int y)
{
if(x >= 1 && x <= n && y >= 1 && y <= m && a[x][y] == 0)
return 1;
return 0;
}
int main()
{
freopen("barbar.in" , "r" , stdin);
freopen("barbar.out" , "w" , stdout);
int i , j , xs , ys , xf , yf;
scanf("%d%d\n" , &n , &m);
priority_queue <dragoni> pq;
for(i = 1 ; i <= n ; i ++)
{
getline(cin , s);
for(j = 0 ; j < m ; j ++)
{
drg[i][j + 1] = INF;
if(s[j] == '*')
a[i][j + 1] = 1;
else if(s[j] == 'I')
{
xs = i;
ys = j + 1;
}
else if(s[j] == 'O')
{
xf = i;
yf = j + 1;
}
else if(s[j] == 'D')
{
temp1.x = i;
temp1.y = j + 1;
pq.push(temp1);
drg[i][j + 1] = 0;
}
}
}
while(!pq.empty())
{
temp1 = pq.top();
pq.pop();
if(drg[temp1.x][temp1.y] < temp1.z)
continue;
for(i = 0 ; i < 4 ; i ++)
{
temp2.x = temp1.x + di[i];
temp2.y = temp1.y + dj[i];
if(valid(temp2.x , temp2.y) && drg[temp2.x][temp2.y] > drg[temp1.x][temp1.y] + 1)
{
drg[temp2.x][temp2.y] = temp2.z = drg[temp1.x][temp1.y] + 1;
pq.push(temp2);
}
}
}
queue <coordonate> q;
d[xs][ys] = drg[xs][ys];
temp3.x = xs;
temp3.y = ys;
q.push(temp3);
while(!q.empty())
{
temp3 = q.front();
q.pop();
for(i = 0 ; i < 4 ; i ++)
{
temp4.x = temp3.x + di[i];
temp4.y = temp3.y + dj[i];
if(valid(temp4.x , temp4.y) && drg[temp4.x][temp4.y] != 0 && d[temp4.x][temp4.y] < d[temp3.x][temp3.y] && d[temp4.x][temp4.y] < drg[temp4.x][temp4.y])
{
d[temp4.x][temp4.y] = min(drg[temp4.x][temp4.y] , d[temp3.x][temp3.y]);
q.push(temp4);
}
}
}
if(d[xf][yf] == 0)
d[xf][yf] = -1;
printf("%d\n" , d[xf][yf]);
return 0;
}