Pagini recente » Cod sursa (job #81298) | Cod sursa (job #2828068) | Cod sursa (job #2809898) | Cod sursa (job #803629) | Cod sursa (job #3341807)
#include <fstream>
#include <queue>
#include <cstring>
using namespace std;
ifstream fin("barbar.in");
ofstream fout("barbar.out");
const int NMAX = 255;
int n, m;
int sx, sy, ex, ey;
int dx[] = {-1, 0, 1, 0};
int dy[] = {0, 1, 0, -1};
int dist[NMAX + 2][NMAX + 2];
bool VIZ[NMAX + 2][NMAX + 2];
char grid[NMAX + 2][NMAX + 2];
queue<pair<int,int>> q;
bool valid(int x)
{
while(!q.empty()) q.pop();
memset(VIZ, 0, sizeof(VIZ));
if(dist[sx][sy] < x)
return false;
q.push({sx, sy});
VIZ[sx][sy] = true;
while(!q.empty())
{
pair<int,int> aux = q.front();
q.pop();
if(aux.first == ex && aux.second == ey)
return true;
for(int dir = 0; dir < 4; dir++)
{
int nx = aux.first + dx[dir];
int ny = aux.second + dy[dir];
if(nx < 1 || nx > n || ny < 1 || ny > m)
continue;
if(!VIZ[nx][ny] &&
grid[nx][ny] != '*' &&
dist[nx][ny] >= x)
{
VIZ[nx][ny] = true;
q.push({nx, ny});
}
}
}
return false;
}
int main()
{
fin >> n >> m;
for(int i = 1; i <= n; i++)
{
char s[NMAX + 2];
fin >> s;
for(int j = 1; j <= m; j++)
{
grid[i][j] = s[j-1];
if(grid[i][j] == 'I')
{
sx = i;
sy = j;
}
if(grid[i][j] == 'O')
{
ex = i;
ey = j;
}
}
}
for(int i = 1; i <= n; i++)
for(int j = 1; j <= m; j++)
dist[i][j] = -1;
for(int i = 1; i <= n; i++)
for(int j = 1; j <= m; j++)
if(grid[i][j] == 'D')
{
dist[i][j] = 0;
q.push({i, j});
}
while(!q.empty())
{
pair<int,int> aux = q.front();
q.pop();
for(int dir = 0; dir < 4; dir++)
{
int nx = aux.first + dx[dir];
int ny = aux.second + dy[dir];
if(nx < 1 || nx > n || ny < 1 || ny > m)
continue;
if(dist[nx][ny] == -1 &&
(grid[nx][ny] == '.' ||
grid[nx][ny] == 'I' ||
grid[nx][ny] == 'O'))
{
dist[nx][ny] =
dist[aux.first][aux.second] + 1;
q.push({nx, ny});
}
}
}
if(dist[ex][ey] == -1)
{
fout << -1;
return 0;
}
int last = 0;
int st = 0;
int dr = dist[ex][ey];
int mij;
while(st <= dr)
{
mij = (st + dr) / 2;
if(valid(mij))
{
last = mij;
st = mij + 1;
}
else
dr = mij - 1;
}
fout << last;
return 0;
}