Pagini recente » Cod sursa (job #2442455) | Cod sursa (job #67595) | Cod sursa (job #1433498) | Cod sursa (job #717347) | Cod sursa (job #2689386)
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
#include <cstring>
using namespace std;
const int nmax = 1000;
char a[nmax + 2][nmax + 2];
queue <pair <int, int> > q;
pair <int, int> aux, nou;
bool viz[nmax + 2][nmax + 2];
pair <int , int> start, finall;
int d[nmax + 2][nmax + 2];
int dx[] = {-1, 0, 1, 0};
int dy[] = {0, 1, 0, -1};
void bfs_pregen()
{
while(!q.empty()) {
aux = q.front();
q.pop();
for(int i = 0; i <= 3; ++i) {
nou = make_pair(aux.first + dx[i], aux.second + dy[i]);
if(a[nou.first][nou.second] != 0 && viz[nou.first][nou.second] == 0 ) {
viz[nou.first][nou.second] = 1;
q.push(nou);
d[nou.first][nou.second] = d[aux.first][aux.second] + 1;
}
}
}
}
void dfs(pair <int, int> x, int k) {
viz[x.first][x.second] = 1;
for(int i = 0; i <= 3; ++i) {
pair <int, int> nx = make_pair(x.first + dx[i], x.second + dy[i]);
if(d[nx.first][nx.second] >= k && a[nx.first][nx.second] != '*' && viz[nx.first][nx.second] == 0) {
dfs(nx, k);
}
}
}
bool check(int k)
{
memset(viz, 0, sizeof(viz));
dfs(start, k);
return viz[finall.first][finall.second];
}
int main()
{
ifstream fin("barbar.in");
ofstream fout("barbar.out");
int n, m;
int st = 0, dr, last = 0;
fin >> n >> m;
for(int i = 1; i <= n; ++i) {
for(int j = 1; j <=m; ++j) {
fin >> a[i][j];
if(a[i][j] == 'D') {
q.push(make_pair(i, j));
viz[i][j] = 1;
}
else if(a[i][j] == '*') {
d[i][j] = -1;
}
else if(a[i][j] == 'I') {
start = make_pair(i, j);
}
else if(a[i][j] == 'O') {
finall = make_pair(i, j);
}
}
}
bfs_pregen();
for(int i = 0; i <= n + 1; ++i) {
d[i][0] = d[i][m + 1] = -1;
}
for(int i = 1; i <= m; ++i) {
d[0][i] = d[n + 1][i] = -1;
}
dr = n + m;
while(st <= dr) {
int med = (st + dr) / 2;
if(check(med)) {
last = med;
st = med + 1;
} else {
dr = med - 1;
}
}
fout << last;
return 0;
}