Cod sursa(job #2810622)

Utilizator icnsrNicula Ionut icnsr Data 29 noiembrie 2021 20:48:06
Problema Componente biconexe Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.28 kb
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <array>

static int N;

struct Room
{
        bool valid() const
        {
                return 0 <= x && x < N && 0 <= y && y < N;
        }

        std::array<Room, 4> neighbours() const
        {
                const std::array<Room, 4> res = {
                    {{x, y - 1}, {x, y + 1}, {x - 1, y}, {x + 1, y}}};

                return res;
        }

        int x, y;
};

int main()
{
        std::freopen("muzeu.in", "r", stdin);
        std::freopen("muzeu.out", "r", stdout);

        std::ios_base::sync_with_stdio(false);
        std::cin.tie(nullptr);

        std::cin >> N;

        std::vector<std::vector<char>> mat(N, std::vector<char>(N));
        std::vector<std::vector<int>> dists(N, std::vector<int>(N, -1));
        std::vector<std::vector<char>> visited(N, std::vector<char>(N, false));
        std::queue<Room> q;
        for(int i = 0; i < N; ++i)
        {
                for(int j = 0; j < N; ++j)
                {
                        std::cin >> mat[i][j];

                        if(mat[i][j] == 'P')
                        {
                                q.push({i, j});
                                dists[i][j] = 0;
                                visited[i][j] = true;
                        }
                        if(mat[i][j] == '#')
                        {
                                dists[i][j] = -2;
                        }
                }
        }

        while(!q.empty())
        {
                const auto c_room = q.front();
                q.pop();

                for(const Room& neigh : c_room.neighbours())
                {
                        if(neigh.valid() && !visited[neigh.x][neigh.y] &&
                           mat[neigh.x][neigh.y] != '#')
                        {
                                q.push(neigh);
                                dists[neigh.x][neigh.y] = dists[c_room.x][c_room.y] + 1;
                                visited[neigh.x][neigh.y] = true;
                        }
                }
        }

        for(int i = 0; i < N; ++i)
        {
                for(int j = 0; j < N; ++j)
                {
                        std::cout << dists[i][j] << ' ';
                }
                std::cout << '\n';
        }
}