Pagini recente » Cod sursa (job #2486381) | Cod sursa (job #3041050) | Cod sursa (job #134779) | Cod sursa (job #1411292) | Cod sursa (job #2235002)
#include <bits/stdc++.h>
#define NM 1002
#define INF 1000000002
using namespace std;
int n, m;
char c[NM][NM];
bool ma[NM][NM];
int sa, sb, fa, fb;
int Ddist[NM][NM];
int mi[NM][NM];
queue < pair <int, int> > q;
int da[] = {-1, 0, 1, 0}, db[] = {0, 1, 0, -1};
bool isok(int a, int b)
{
return (a >= 1 && a <= n && b >= 1 && b <= m);
}
void Dbfs()
{
while(!q.empty())
{
pair <int, int> f = q.front();
q.pop();
for(int i = 0; i < 4; i++)
{
int f1 = f.first + da[i], f2 = f.second + db[i];
if(isok(f1, f2) && ma[f1][f2] == 0 && Ddist[f1][f2] > Ddist[f.first][f.second] + 1)
{
q.push(make_pair(f1, f2));
Ddist[f1][f2] = Ddist[f.first][f.second] + 1;
}
}
}
}
void bfs(int a, int b)
{
q.push(make_pair(a, b));
mi[a][b] = Ddist[a][b];
while(!q.empty())
{
pair <int, int> f = q.front();
q.pop();
for(int i = 0; i < 4; i++)
{
int f1 = f.first + da[i], f2 = f.second + db[i];
if(isok(f1, f2) && ma[f1][f2] == 0 && mi[f1][f2] < min(mi[f.first][f.second], Ddist[f1][f2]))
{
q.push(make_pair(f1, f2));
mi[f1][f2] = min(mi[f.first][f.second], Ddist[f1][f2]);
}
}
}
}
int main()
{
ifstream fin ("barbar.in");
ofstream fout ("barbar.out");
fin >> n >> m;
for(int i = 1; i <= n; i++)
for(int j = 1; j <= m; j++)
{
fin >> c[i][j];
if(c[i][j] == '*')
ma[i][j] = 1;
else if(c[i][j] == 'I')
{
sa = i;
sb = j;
}
else if(c[i][j] == 'O')
{
fa = i;
fb = j;
}
Ddist[i][j] = INF;
mi[i][j] = -1;
}
for(int i = 1; i <= n; i++)
for(int j = 1; j <= m; j++)
if(c[i][j] == 'D')
{
q.push(make_pair(i, j));
Ddist[i][j] = 0;
}
Dbfs();
bfs(sa, sb);
fout << mi[fa][fb] << "\n";
return 0;
}