Pagini recente » Cod sursa (job #771457) | Cod sursa (job #1883398) | Cod sursa (job #1176233) | Cod sursa (job #1443976) | Cod sursa (job #2904993)
#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);
for (int i = 0; i < n; i++) {
visited[i] = 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;
int cnt = 0;
while (!q.empty()) {
// Extract the current node from the queue
int curr = q.front();
q.pop();
if (curr == 6) {
while(1);
}
// 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
while(1);
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]);
}
*/
}