-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbfs.cpp
More file actions
74 lines (58 loc) · 1.47 KB
/
bfs.cpp
File metadata and controls
74 lines (58 loc) · 1.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <bits/stdc++.h>
using namespace std;
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
void bfs(int s, int n, const vector<vector<int>>& adj, vector<int>& d, vector<int>& p) {
queue<int>q;
vector<bool>vis(n,false);
vis[s]=1;
d[s]=0;
p[s]=-1;
q.push(s);
while(!q.empty()){
int node=q.front();
q.pop();
for(auto nbr:adj[node]){
if(!vis[nbr]){
vis[nbr]=1;
d[nbr]=d[node]+1;
p[nbr]=node;
q.push(nbr);
}
}
}
}
int main() {
// Number of nodes (0 through 5)
int n = 6;
// Adjacency list representation of the graph
vector<vector<int>> adj(n);
// Creating a sample undirected graph:
// 0 --- 1 --- 3
// | |
// 2 --- 4 --- 5
adj[0] = {1, 2};
adj[1] = {0, 3};
adj[2] = {0, 4};
adj[3] = {1, 5};
adj[4] = {2, 5};
adj[5] = {3, 4};
int source = 0;
// Output vectors for distances and parents
vector<int> d(n, -1); // Initialize distances to -1 (representing unreachable)
vector<int> p(n, -1); // Initialize parents to -1
// Run BFS
bfs(source, n, adj, d, p);
// Print the shortest distances from the source
cout << "Shortest distances from node " << source << ":\n";
for (int i = 0; i < n; ++i) {
if (d[i] != -1) {
cout << "Node " << i << " -> Distance: " << d[i] << " (Parent: " << p[i] << ")\n";
} else {
cout << "Node " << i << " -> Unreachable\n";
}
}
return 0;
}