Cod sursa(job #3314730)

Utilizator LucaSerbanLuca Serban LucaSerban Data 10 octombrie 2025 20:24:04
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.43 kb
// BFS_ex_arena.cpp : This file contains the 'main' function. Program execution begins and ends there.
//

#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

int n, m, s;

std::ifstream in("bfs.in");
std::ofstream out("bfs.out");

void listadeadiacenta(std::vector<std::vector<int>>& G, bool isOriented)
{
    int x, y;
    for (int i = 0; i < m; ++i) {
        in >> x >> y;
        if (isOriented) {
            G[x].push_back(y);
        }
        else {
            G[x].push_back(y);
            G[y].push_back(x);
        }
    }
}

void BFS(std::vector<std::vector<int>>& G, std::vector<bool>& visited, std::vector<int>& distance, int start)
{
	std::queue<int> queue;
    visited[start] = true;
    distance[start] = 0;
	queue.push(start);
    while (!queue.empty())
    {
        int current = queue.front();
        queue.pop();
        for (auto neighbor : G[current])
        {
            if (!visited[neighbor])
            {
				queue.push(neighbor);
				visited[neighbor] = true;
                distance[neighbor] = distance[current] + 1;
            }
        }
    }
}


int main()
{
	in >> n >> m >> s;
    std::vector <std::vector <int> > G(n + 1);
	listadeadiacenta(G, true);
    std::vector<int> distance(n + 1, -1);
	std::vector<bool> visited(n + 1, false); 
	BFS(G, visited, distance, s);
    for (int i = 1; i <= n; i++)
		out << distance[i] << ' '; 
}