Pagini recente » Cod sursa (job #562991) | Cod sursa (job #502780) | Cod sursa (job #3127468) | Cod sursa (job #1087780) | Cod sursa (job #2165319)
#include <bits/stdc++.h>
using namespace std;
ifstream in("barbar.in");
ofstream out("barbar.out");
int n,m,dp[1005][1005],cost[1005][1005];
int dx[] = {1,-1,0,0};
int dy[] = {0,0,1,-1};
const int INF = 1<<30;
bool ok(int i, int j)
{
return (i>=1 && i<=n && j>=1 && j<=m);
}
char v[1005][1005];
int main()
{
int x1,y1,x2,y2;
queue< pair<int,int> > q;
in >> n >> m;
for (int i = 1; i<=n; i++)
for (int j = 1; j<=m; j++)
{
in >> v[i][j];
if (v[i][j] == 'D')
{
q.push(make_pair(i,j));
dp[i][j] = 0;
}
else
{
if (v[i][j] == 'I')
{
x1 = i;
y1 = j;
}
else if (v[i][j] == 'O')
{
x2 = i;
y2 = j;
}
dp[i][j] = INF;
}
}
while (!q.empty())
{
int i = q.front().first;
int j = q.front().second;
for (int z = 0; z<4; z++)
{
int i2 = i+dx[z];
int j2 = j+dy[z];
if (ok(i2,j2) && dp[i2][j2]>dp[i][j]+1)
{
dp[i2][j2] = 1+dp[i][j];
q.push(make_pair(i2,j2));
}
}
q.pop();
}
q.push(make_pair(x1,y1));
cost[x1][y1] = dp[x1][y1];
while (!q.empty())
{
int i = q.front().first;
int j = q.front().second;
for (int z = 0; z<4; z++)
{
int i2 = i+dx[z];
int j2 = j+dy[z];
if (ok(i2,j2) && (v[i2][j2] == '.' || v[i2][j2] == 'O'))
{
if (cost[i2][j2]<min(cost[i][j],dp[i2][j2]))
{
cost[i2][j2] = min(cost[i][j],dp[i2][j2]);
q.push(make_pair(i2,j2));
}
}
}
q.pop();
}
out << (cost[x2][y2] ? cost[x2][y2] : -1);
}