Pagini recente » Cod sursa (job #1232923) | Cod sursa (job #2656277) | Cod sursa (job #864756) | Cod sursa (job #1039422) | Cod sursa (job #2165366)
#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;
char v[1005][1005];
bool ok(int i, int j)
{
return (i>=1 && i<=n && j>=1 && j<=m && v[i][j]!='*');
}
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();
}
for (int i = 1; i<=n; i++)
for (int j = 1; j<=m; j++)
cost[i][j] = -1;
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))
{
if (cost[i2][j2] == -1)
{
cost[i2][j2] = min(dp[i2][j2],cost[i][j]);
q.push(make_pair(i2,j2));
}
else 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];
}