Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "bits/stdc++.h"
- using namespace std;
- const int maxN = 100;
- bool visited[maxN];
- int cost[maxN];
- vector<int> adj[maxN];
- void bfs (int source) {
- queue<int> q;
- q.push(source);
- cost[source] = 0;
- visited[source] = true;
- while (!q.empty()) {
- int u = q.front();
- q.pop();
- for (int v : adj[u]) {
- if (!visited[v]) {
- cost[v] = cost[u] + 1;
- visited[v] = true;
- q.push(v);
- }
- }
- }
- }
- int main () {
- int n = 5, m = 5;
- for (int i = 1; i <= m; ++i) {
- int u, v;
- cin >> u >> v;
- adj[u].push_back(v);
- adj[v].push_back(u);
- }
- bfs(1);
- for (int i = 1; i <= n; ++i) cout << cost[i] << ' ';
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement