Pagini recente » Cod sursa (job #2215029) | Cod sursa (job #1933313) | Cod sursa (job #1310807) | Cod sursa (job #1360643) | Cod sursa (job #1535015)
#include <bits/stdc++.h>
using namespace std;
ofstream fout("barbar.out");
int n, m, cmax, xo, yo, xi, yi;
int b[1005][1005], c[1005][1005];
char a[1005][1005];
stack <pair <int, int> > st;
struct Coord
{
int x, y;
};
queue <Coord> q;
void Citire()
{
int i, j;
Coord w;
ifstream fin("barbar.in");
fin >> n >> m;
for(i = 1; i <= n; i++)
for(j = 1; j <= m; j++)
{
fin >> a[i][j];
if(a[i][j] == 'D')
{
w.x = i;
w.y = j;
q.push(w);
}
if(a[i][j] == 'O')
{
xo = i;
yo = j;
}
if(a[i][j] == 'I')
{
xi = i;
yi = j;
}
}
fin.close();
}
void Bordare()
{
int i;
for(i = 0; i <= n + 1; i++)
a[i][0] = a[i][m + 1] = '*';
for(i = 0; i <= m + 1; i++)
a[0][i] = a[n + 1][i] = '*';
}
void Lee()
{
int dx[] = {1, -1, 0, 0};
int dy[] = {0, 0, 1, -1};
int i, j, x, y, k;
Coord w, w1;
while(!q.empty())
{
w = q.front();
x = w.x;
y = w.y;
q.pop();
for(k = 0; k < 4; k++)
{
i = x + dx[k];
j = y + dy[k];
if(a[i][j] == '.' &&
(b[i][j] == 0 || b[i][j] > b[x][y] + 1))
{
b[i][j] = b[x][y] + 1;
w1.x = i;
w1.y = j;
q.push(w1);
}
else cmax = max(cmax, b[i][j]);
}
}
for(i = 1; i <= n; i++)
for(j = 1; j <= m ;j++)
c[i][j] = b[i][j];
//fout<<cmax;
}
void Fill(int i, int j, int val)
{
b[i][j] = -1;
st.push(make_pair(i, j));
while(!st.empty())
{
i = st.top().first;
j = st.top().second;
st.pop();
if(b[i + 1][j] >= val || b[i + 1][j] == -2)
{
b[i + 1][j] = -1;
st.push(make_pair(i + 1, j));
}
if(b[i - 1][j] >= val || b[i - 1][j] == -2)
{
b[i - 1][j] = -1;
st.push(make_pair(i - 1, j));
}
if(b[i][j + 1] >= val || b[i][j + 1] == -2)
{
b[i][j + 1] = -1;
st.push(make_pair(i, j + 1));
}
if(b[i][j - 1] >= val || b[i][j - 1] == -2)
{
b[i][j - 1] = -1;
st.push(make_pair(i, j - 1));
}
}
}
void CautBin()
{
int i, j, mij, st, dr, sol;
st = 1;
dr = cmax;
sol = -1;
while(st <= dr)
{
for(i = 1; i <= n; i++)
for(j = 1; j <= m; j++)
b[i][j] = c[i][j];
b[xo][yo] = -2;
mij = (st + dr) / 2;
Fill(xi, yi, mij);
if(b[xo][yo] == -1)
{
sol = mij;
st = mij + 1;
}
else dr = mij - 1;
}
fout<<sol;
}
int main()
{
Citire();
Bordare();
Lee();
CautBin();
return 0;
}