Cod sursa(job #3042269)

Utilizator pluca82popa Luca pluca82 Data 5 aprilie 2023 11:09:21
Problema Rj Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.83 kb
#include <bits/stdc++.h>
using namespace std;

ifstream fin("rj.in");
ofstream fout("rj.out");

const int NMAX = 105;
const int dx[] = {1, 1, 0, -1, -1, -1, 0, 1};
const int dy[] = {0, 1, 1, 1, 0, -1, -1, -1};

int n, m;
char mat[NMAX][NMAX];
int dist[NMAX][NMAX];
int sx, sy, fx, fy;

bool in_bounds(int x, int y) {
    return x >= 1 && x <= n && y >= 1 && y <= m;
}

void read() {
    fin >> n >> m;
    for (int i = 1; i <= n; ++i) {
        for (int j = 1; j <= m; ++j) {
            fin >> mat[i][j];
            if (mat[i][j] == 'R') {
                sx = i;
                sy = j;
            } else if (mat[i][j] == 'J') {
                fx = i;
                fy = j;
            }
        }
    }
}

void lee() {
    queue<pair<int, int>> q;
    q.push({sx, sy});
    memset(dist, -1, sizeof(dist));
    dist[sx][sy] = 0;

    while (!q.empty()) {
        auto [x, y] = q.front();
        q.pop();
        for (int k = 0; k < 8; ++k) {
            int nx = x + dx[k];
            int ny = y + dy[k];
            if (in_bounds(nx, ny) && mat[nx][ny] != 'X' && dist[nx][ny] == -1) {
                dist[nx][ny] = dist[x][y] + 1;
                q.push({nx, ny});
            }
        }
    }
}

int main() {
    read();
    lee();

    int ans_x = 1, ans_y = 1;
    int ans_dist = dist[1][1] + dist[fx][fy];
    for (int i = 1; i <= n; ++i) {
        for (int j = 1; j <= m; ++j) {
            if (mat[i][j] != 'X' && dist[i][j] != -1) {
                int cur_dist = dist[i][j] + dist[fx][fy];
                if (cur_dist < ans_dist || (cur_dist == ans_dist && i < ans_x) || (cur_dist == ans_dist && i == ans_x && j < ans_y)) {
                    ans_dist = cur_dist;
                    ans_x = i;
                    ans_y = j;
                }
            }
        }
    }

    fout << ans_x << " " << ans_y << " " << ans_dist << "\n";

    return 0;
}