Cod sursa(job #1821597)

Utilizator tudortarniceruTudor Tarniceru tudortarniceru Data 3 decembrie 2016 12:55:05
Problema Barbar Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.29 kb
#include <fstream>
#include <algorithm>
#include <cstring>
#include <vector>
#include <climits>
#include <iostream>
using namespace std;
ifstream fin("barbar.in");
ofstream fout("barbar.out");

const int MAXN = 1005;
int n, m;
int v[MAXN][MAXN], a[MAXN][MAXN];
char f[MAXN];
int x1, y1, x2, y2;
vector<int> c[3];
int d1[10] = {0, -1, 0, 1, 0};
int d2[10] = {0, 0, 1, 0, -1};

void border() {
    for (int i = 0; i <= n + 1; ++i) {
        v[i][0] = -1;
        v[i][m + 1] = -1;
    }
    for (int i = 0; i <= m + 1; ++i) {
        v[0][i] = -1;
        v[n + 1][i] = -1;
    }
}

int main() {
    fin >> n >> m;
    for (int i = 1; i <= n; ++i) {
        fin >> f;
        for (int j = 0; j < m; ++j) {
            if (f[j] == '*') {
                v[i][j + 1] = -1;
            }
            else if (f[j] == 'D') {
                v[i][j + 1] = -1;
                c[1].push_back(i);
                c[2].push_back(j + 1);
            }
            else if (f[j] == 'I') {
                x1 = i;
                y1 = j + 1;
            }
            else if (f[j] == 'O') {
                x2 = i;
                y2 = j + 1;
            }
        }
    }
    border();
    int ci = 0;
    while (ci < c[1].size()) {
        int x = c[1][ci];
        int y = c[2][ci];
        for (int k = 1; k <= 4; ++k) {
            int lin = x + d1[k];
            int col = y + d2[k];
            if (a[lin][col] == 0 && v[lin][col] != -1) {
                a[lin][col] = a[x][y] + 1;
                c[1].push_back(lin);
                c[2].push_back(col);
            }
        }
        ci++;
    }

    c[1].clear();
    c[2].clear();
    ci = 0;
    v[x1][y1] = a[x1][y1];
    c[1].push_back(x1);
    c[2].push_back(y1);

    while (ci < c[1].size()) {
        int x = c[1][ci];
        int y = c[2][ci];
        for (int k = 1; k <= 4; ++k) {
            int i = x + d1[k];
            int j = y + d2[k];
            if (v[i][j] != -1) {
                if (v[x][y] > v[i][j]) {
                    v[i][j] = min(a[i][j], v[x][y]);
                    c[1].push_back(i);
                    c[2].push_back(j);
                }
            }
        }
        ci++;
    }

    fout << v[x2][y2];
    fout.close();
    return 0;
}