-
Notifications
You must be signed in to change notification settings - Fork 93
Expand file tree
/
Copy pathBFS.cpp
More file actions
78 lines (60 loc) · 1.88 KB
/
BFS.cpp
File metadata and controls
78 lines (60 loc) · 1.88 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
75
76
77
78
#include <iostream>
#include <queue>
#include <vector>
#include <iomanip>
using namespace std;
//COPY THE BLACKBOX, there is no need to change anything in it.
//Check the main function at bottom for USAGE
//****************BLACKBOX START*****************
//START COPYING FROM HERE
class Graph {
public:
Graph(int num_nodes)
: adj_list(num_nodes), dist(num_nodes, -1) {}
void add_edge(int start, int end);
vector<vector<int>> adj_list;
vector<int> dist;
};
void Graph::add_edge(int start, int end) {
adj_list[start].push_back(end);
}
vector<int> BFS(Graph& g, int source) {
vector<bool> visited(g.adj_list.size(), false);
queue<int> q;
q.push(source);
visited[source] = true;
g.dist[source] = 0;
while(!q.empty()) {
int cur_node = q.front();
vector<int> cur_node_adj = g.adj_list[cur_node];
for (unsigned int i = 0; i < cur_node_adj.size(); ++i) {
int adj_node = cur_node_adj[i];
if (visited[adj_node] == false) {
visited[adj_node] = true;
g.dist[adj_node] = g.dist[cur_node] + 1;
q.push(adj_node);
}
}
q.pop();
}
return g.dist;
}
//END COPYING HERE
//********************BLACKBOX END******************
int main() {
// initaitise a graph with 4 nodes, nodes are 0-indexed
Graph g(4);
//DIRECTED GRAPH : add edges `Node 0 -> Node 4` and `Node 1 -> Node 3`
g.add_edge(0,4);
g.add_edge(1,3);
//UNDIRECT GRAPH : add edges between `Node 0 -- Node 4` and `Node 1 -- Node 3`
g.add_edge(0,4);
g.add_edge(4,0);
g.add_edge(1,3);
g.add_edge(3,1);
//do BFS on the graph g start at `Node 2`
//An array of size "number of nodes" is returned with the minimum distance from `Node 2` to each node, i.e. `shortest path length from Node 2 -> Node 3 = min_dist[3] `
//If a `Node i` is unreachable from `Node 2`, then `min_dist[i]=-1`
vector<int>min_dist = BFS(g, 2);
return 0;
}