Cod sursa(job #2904979)

Utilizator RazorBestPricop Razvan Marius RazorBest Data 18 mai 2022 23:29:15
Problema BFS - Parcurgere in latime Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.32 kb
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <queue>

using namespace std;

void bfs(int src, vector<vector<int>> &graph, vector<int> &dist) {
	int n = graph.size();
	queue<int> q;
	// Initialise with 0 a vector of n elements
	vector<int> visited(n, 0);

	// Initialise the distances with -1
	for (int i = 0; i < n; i++) {
		dist[i] = -1;
	}

	// Push the starting node on the queue
	q.push(src);
	dist[src] = 0;
	visited[src] = 1;

	while (!q.empty()) {
		// Extract the current node from the queue
		int curr = q.front();
		q.pop();

		// Iterate through the neighbours of curr
		for (size_t i = 0; i < graph[curr].size(); i++) {
			int next = graph[curr][i];
			// If node i is not visited, then put it on the queue
			if (!visited[next]) {
				visited[next] = 1;
				q.push(next);
				// dist[curr] was calculated previously
				dist[next] = dist[curr] + 1;
			}
		}
	}
}

int main() {
	int n, m;
	int src;

	scanf("%d%d%d", &n, &m, &src);
	src--;

	// Data structure for holding the edges of the graph
	vector<vector<int>> graph(n);

	// Vector of distances from src
	// dist[i] = minimum distance from src to i
	vector<int> dist(n);

	for (int i = 0; i < m; i++) {
		int x, y;
		scanf("%d%d", &x, &y);
		graph[x - 1].push_back(y - 1);
	}

	bfs(src, graph, dist);

	for (int i = 0; i < n; i++) {
		printf("%d ", dist[i]);
	}
}