Pagini recente » Cod sursa (job #1355112) | Cod sursa (job #1165280) | Cod sursa (job #2910525) | Cod sursa (job #1949861) | Cod sursa (job #2712748)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("barbar.in");
ofstream fout("barbar.out");
int n, m;
int v[1022][1022];
int w[1022][1022];
int startlin, startcol, stoplin, stopcol;
queue<pair<int,int>> coada;
int viz[1020][1020];
int di[4] = {0,0,-1,1};
int dj[4] = {1,-1,0,0};
bool verifica(int i, int j)
{
if(i < 1 || j < 1 || i > n || j > n)
return false;
if(v[i][j] == -1)
return false;
return true;
}
void Lee()
{
for(int i = 1; i <= n; i ++)
{
for(int j = 1; j <= n; j ++)
{
if(v[i][j] == 0)
v[i][j] = 1e7;
}
}
while(!coada.empty())
{
int lin = coada.front().first;
int col = coada.front().second;
coada.pop();
for(int i = 0; i < 4; i ++)
{
int linie_noua = lin + di[i];
int coloana_noua = col + dj[i];
if(verifica(linie_noua,coloana_noua) && v[lin][col] + 1 < v[linie_noua][coloana_noua])
{
v[linie_noua][coloana_noua] = v[lin][col] + 1;
coada.push(make_pair(linie_noua,coloana_noua));
}
}
}
for(int i = 1; i <= n; i ++)
{
for(int j = 1; j <= n; j ++)
{
if(v[i][j] == 1e7)
v[i][j] = -1;
else if(v[i][j] > 0)
v[i][j] --;
}
}
}
int parcurgere(int val)
{
for(int i = 1; i <= n; i ++)
{
for(int j = 1; j <= n; j ++)
{
w[i][j] = 1e7;
viz[i][j] = 0;
}
}
w[startlin][startcol] = 0;
viz[startlin][startcol] = 1;
coada.push(make_pair(startlin,startcol));
while(!coada.empty())
{
int l = coada.front().first;
int c = coada.front().second;
coada.pop();
for(int i = 0; i < 4; i ++)
{
int lnou = l + di[i];
int cnou = c + dj[i];
if(verifica(lnou,cnou) && v[lnou][cnou] >= val && viz[lnou][cnou] == 0)
{
viz[lnou][cnou] = 1;
w[lnou][cnou] = w[l][c];
coada.push(make_pair(lnou,cnou));
}
}
}
if(w[stoplin][stopcol] == 0)
return 0;
return 1;
}
int main()
{
fin >> n >> m;
for(int i = 1; i <= n; i ++)
{
for(int j = 1; j <= n; j ++)
{
char c;
fin >> c;
if(c == 'D')
{
coada.push(make_pair(i,j));
v[i][j] = 1;
}
if(c == 'I')
{
startlin = i;
startcol = j;
}
if(c == 'O')
{
stoplin = i;
stopcol = j;
}
if(c == '*')
{
v[i][j] = -1;
}
}
}
Lee();
int st = 0, dr = n * m;
int ans = 0;
while(st <= dr)
{
int mijloc = (st + dr) / 2;
int sol = -1;
sol = parcurgere(mijloc);
if(sol == 0)
{
st = mijloc + 1;
ans = mijloc;
}
else
dr = mijloc - 1;
}
if(ans)
fout << ans << '\n';
else
fout << -1 << '\n';
return 0;
}