Pagini recente » Cod sursa (job #2664078) | Cod sursa (job #2802680) | Cod sursa (job #1438512) | Cod sursa (job #452477) | Cod sursa (job #2667820)
#include <fstream>
#include <queue>
using namespace std;
const int LMAX = 1000;
const int CMAX = 1000;
int l, c;
int temnita[2 + LMAX][2 + CMAX];
int viz[2 + LMAX][2 + CMAX];
bool obs[2 + LMAX][2 + CMAX];
pair<int, int> start, stop;
queue<pair<int, int> > q;
int dx[] = {1, 0, -1, 0};
int dy[] = {0, 1, 0, -1};
void fill()
{
while (!q.empty())
{
int x = q.front().first;
int y = q.front().second;
q.pop();
for(int i = 0; i < 4; i++)
{
int x_crt = x + dx[i];
int y_crt = y + dy[i];
if(!obs[x_crt][y_crt] && temnita[x_crt][y_crt] == 0)
{
temnita[x_crt][y_crt] = temnita[x][y] + 1;
q.push(make_pair(x_crt, y_crt));
}
}
}
}
bool bfs(int maxim)
{
while(!q.empty())
{
q.pop();
}
viz[start.first][start.second] = maxim;
q.push(start);
while(!q.empty())
{
int x = q.front().first;
int y = q.front().second;
q.pop();
for(int i = 0; i < 4; i++)
{
int x_crt = x + dx[i];
int y_crt = y + dy[i];
if (!obs[x_crt][y_crt] && viz[x_crt][y_crt] != maxim && temnita[x_crt][y_crt] >= maxim)
{
viz[x_crt][y_crt] = maxim;
q.push(make_pair(x_crt, y_crt));
if(x_crt == stop.first && y_crt == stop.second)
{
return true;
}
}
}
}
return false;
}
int main()
{
ifstream in("barbar.in");
ofstream out("barbar.out");
char ch;
in >> l >> c;
for (int i = 1; i <= l; i++)
{
for (int j = 1; j <= c; j++)
{
in >> ch;
if (ch == 'I')
{
start.first = i;
start.second = j;
}
else if (ch == '*')
{
obs[i][j] = true;
}
else if (ch == 'O')
{
stop.first = i;
stop.second = j;
}
else if (ch == 'D')
{
obs[i][j] = true;
q.push(make_pair(i, j));
}
}
}
for(int i = 0; i <= l + 1; i++)
{
obs[i][0] = true;
obs[i][c + 1] = true;
}
for(int j = 0; j <= c + 1; j++)
{
obs[0][j] = true;
obs[l + 1][j] = true;
}
fill();
int st = 1, dr = temnita[start.first][start.second], last = - 1;
while(st <= dr)
{
int mij = (st + dr)/2;
if(bfs(mij))
{
st = mij + 1;
last = mij;
}
else
{
dr = mij - 1;
}
}
out << last;
/*
for(int i = 1; i <= l; i++)
{
for(int j = 1; j <= c; j++)
{
out << temnita[i][j] << ' ';
}
out << '\n';
}
*/
return 0;
}