Cod sursa(job #2786196)

Utilizator qubitrubbitQubit Rubbit qubitrubbit Data 20 octombrie 2021 15:21:28
Problema BFS - Parcurgere in latime Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.57 kb
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

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

class Graph
{
private:
    int cntNodes;
    vector<vector<int>> adjList;

public:
    Graph(int n)
    {
        cntNodes = n;
        for (int i = 0; i < n; ++i)
        {
            adjList.push_back(vector<int>());
        }
    }

    void addEdge(int from, int to, bool oriented)
    {
        adjList[from].push_back(to);
        if (!oriented)
        {
            adjList[to].push_back(from);
        }
    }

    void bfs(int source)
    {
        bool visited[cntNodes];
        fill(visited, visited + cntNodes, false);
        visited[source] = true;

        int dist[cntNodes];
        fill(dist, dist + cntNodes, -1);
        dist[source] = 0;

        queue<int> q;
        q.push(source);
        while (!q.empty())
        {
            int top = q.front();
            q.pop();
            for (int childId : adjList[top])
            {
                if (!visited[childId])
                {
                    dist[childId] = dist[top] + 1;
                    visited[childId] = true;
                    q.push(childId);
                }
            }
        }
        for (int i = 0; i < cntNodes; ++i)
        {
            fout << dist[i] << " ";
        }
    }
};

int n, m, a, b, s;
int main()
{
    fin >> n >> m >> s;
    Graph g(n);
    while (m-- > 0)
    {
        fin >> a >> b;
        g.addEdge(a - 1, b - 1, true);
    }
    g.bfs(s - 1);
    return 0;
}