Cod sursa(job #1821600)

Utilizator tudortarniceruTudor Tarniceru tudortarniceru Data 3 decembrie 2016 12:55:56
Problema Barbar Scor 50
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 xi, yi, xf, yf;
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') {
                xi = i;
                yi = j + 1;
            }
            else if (f[j] == 'O') {
                xf = i;
                yf = 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[xi][yi] = a[xi][yi];
    c[1].push_back(xi);
    c[2].push_back(yi);

    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[xf][yf];
    fout.close();
    return 0;
}