Pagini recente » Borderou de evaluare (job #2427975) | Borderou de evaluare (job #2016483) | Borderou de evaluare (job #2020190) | Borderou de evaluare (job #113471) | Cod sursa (job #2169903)
/*
* "El este inteligent.. pare lent dar nu e lent, pentru ca e inteligent si paseaza foarte bine"
* - Gheorghe Hagi
*/
#include <iostream>
#include <fstream>
#include <queue>
using namespace std;
ifstream f ("barbar.in" );
ofstream g ("barbar.out");
static const int NMax = 1e3 + 5;
static const int INF = 2e9;
int n, m;
int dp[NMax][NMax], cost[NMax][NMax];
int dx[] = {-1, 0, 1, 0};
int dy[] = { 0, 1, 0, -1};
struct hagi {
int x, y;
}start, fin;
string A[NMax];
queue < pair<int, int> > q;
bool ok(int x, int y) {
if(x > 0 && x < n + 1 && y > 0 && y < m + 1 && A[x][y] != '*') return true;
return false;
}
void bfs() {
while(!q.empty()) {
int l = q.front().first;
int c = q.front().second;
for(int dir = 0; dir < 4; ++dir) {
int newL = l + dx[dir];
int newC = c + dy[dir];
if(ok(newL, newC)) {
if(dp[newL][newC] > dp[l][c] + 1) {
dp[newL][newC] = dp[l][c] + 1;
q.push(make_pair(newL, newC));
}
}
}
q.pop();
}
cost[start.x][start.y] = dp[start.x][start.y];
q.push(make_pair(start.x, start.y));
while(!q.empty()) {
int l = q.front().first;
int c = q.front().second;
for(int dir = 0; dir < 4; ++dir) {
int newL = l + dx[dir];
int newC = c + dy[dir];
if(ok(newL, newC)) {
if(cost[newL][newC] == -1 || cost[newL][newC] < min(dp[newL][newC], cost[l][c])) {
cost[newL][newC] = min(dp[newL][newC], cost[l][c]);
q.push(make_pair(newL, newC));
}
}
}
q.pop();
}
g << cost[fin.x][fin.y] << ' ';
}
int main()
{
f >> n >> m;
for(int i = 1; i <= n; ++i) {
f >> A[i];
A[i] = ' ' + A[i];
for(int j = 1; j <= m; ++j) {
dp[i][j] = INF;
if(A[i][j] == 'I') {
start.x = i;
start.y = j;
} else if(A[i][j] == 'O') {
fin.x = i;
fin.y = j;
} else if(A[i][j] == 'D') {
q.push(make_pair(i, j));
dp[i][j] = 0;
}
cost[i][j] = -1;
}
}
bfs();
f.close();
g.close();
return 0;
}