Pagini recente » Cod sursa (job #1994674) | Istoria paginii runda/oni_2011_ziua1_clasele_xi-xii | Cod sursa (job #691047) | Cod sursa (job #2786267) | Cod sursa (job #1825032)
#include <iostream>
#include <fstream>
#include <queue>
#include <algorithm>
using namespace std;
ifstream in("barbar.in");
ofstream out("barbar.out");
const int nMax = 1005;
const int mMax = 1005;
const int INF = nMax * mMax;
const int dx[] = {0, 0, -1, 1};
const int dy[] = {-1, 1, 0, 0};
int n, m;
char a[nMax][mMax];
int dist[nMax][mMax]; //distanta din punctul i, j pana la cel mai apropiat dragon
bool vizD[nMax][mMax];
queue<pair<int, int> > qD; //coada dragonilor
int dp[nMax][mMax];
bool viz[nMax][mMax];
int startX, startY;
int stopX, stopY;
void citire()
{
in >> n >> m;
for(int i = 1; i <= n; ++i)
for(int j = 1; j <= m; ++j)
{
in >> a[i][j];
dist[i][j] = INF;
dp[i][j] = -1;
if(a[i][j] == 'I')
{
startX = i;
startY = j;
}
else if(a[i][j] == 'O')
{
stopX = i;
stopY = j;
}
else if(a[i][j] == 'D')
{
qD.push(make_pair(i, j));
vizD[i][j] = true;
dist[i][j] = 0;
}
}
for(int i = 0; i <= n + 1; ++i)
{
a[i][0] = '*';
a[i][m + 1] = '*';
}
for(int j = 0; j <= m + 1; ++j)
{
a[0][j] = '*';
a[n + 1][j] = '*';
}
}
void SetareDistante()
{
pair<int, int> p;
int newx, newy;
while(qD.empty() == false)
{
p = qD.front();
qD.pop();
vizD[p.first][p.second] = false;
for(int d = 0; d < 4; ++d)
{
newx = p.first + dx[d];
newy = p.second + dy[d];
if(dist[newx][newy] > dist[p.first][p.second] + 1)
{
dist[newx][newy] = dist[p.first][p.second] + 1;
if(vizD[newx][newy] == false)
{
qD.push(make_pair(newx, newy));
vizD[newx][newy] = true;
}
}
}
}
}
void rezolvare()
{
SetareDistante();
queue<pair<int, int> > q;
dp[startX][startY] = dist[startX][startY];
q.push(make_pair(startX, startY));
viz[startX][startY] = true;
pair<int, int> p;
int newx, newy;
while(q.empty() == false)
{
p = q.front();
q.pop();
viz[p.first][p.second] = false;
for(int d = 0; d < 4; ++d)
{
newx = p.first + dx[d];
newy = p.second + dy[d];
if(a[newx][newy] != '*' && dp[newx][newy] < dp[p.first][p.second])
{
dp[newx][newy] = min(dist[newx][newy], dp[p.first][p.second]);
if(viz[newx][newy] == false)
{
q.push(make_pair(newx, newy));
viz[newx][newy] = true;
}
}
}
}
out << dp[stopX][stopY] << "\n";
}
int main()
{
citire();
rezolvare();
return 0;
}