-
Notifications
You must be signed in to change notification settings - Fork 158
/
Copy path02_implement_BFS_algorithm.cpp
90 lines (67 loc) · 2.05 KB
/
02_implement_BFS_algorithm.cpp
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
79
80
81
82
83
84
85
86
87
88
89
90
/*
link: https://practice.geeksforgeeks.org/problems/bfs-traversal-of-graph/1
sol: https://www.geeksforgeeks.org/breadth-first-search-or-bfs-for-a-graph/
video: https://youtu.be/UeE67iCK2lQ?list=PLgUwDviBIf0rGEWe64KWas0Nryn7SCRWw
travel adjacent node first
than move to the next node
The Time complexity of BFS is O(V + E) when Adjacency List is used
and O(V^2) when Adjacency Matrix is used,
where V stands for vertices and E stands for edges.
as it will go to every vertex as well as it will check for corresponding edges
hence TC becomes V+E
*/
// ----------------------------------------------------------------------------------------------------------------------- //
/*
for connected component
*/
vector<int> bfsOfGraph(int V, vector<int> adj[])
{
vector<bool> vis(V, false);
vector<int> ans;
queue<int> q;
q.push(0);
vis[0] = 1;
while (!q.empty()) {
int curr = q.front();
q.pop();
ans.push_back(curr);
for (auto j : adj[curr]) {
if (!vis[j]) {
q.push(j);
vis[j] = 1;
}
}
}
return ans;
}
// ----------------------------------------------------------------------------------------------------------------------- //
/*
for disconnected component
TC: O(N + E) => visiting every node once
SC: O(N + E) => space for every node and vice-verca for both edge
*/
vector<int> bfsOfGraph(int V, vector<int> adj[])
{
vector<bool> vis(V, false);
vector<int> ans;
for (int i = 0;i < V;i++) {
if (!vis[i]) {
int i = 0;
queue<int> q;
q.push(i);
vis[i] = 1;
while (!q.empty()) {
int curr = q.front();
q.pop();
ans.push_back(curr);
for (auto j : adj[curr]) {
if (!vis[j]) {
q.push(j);
vis[j] = 1;
}
}
}
}
return ans;
}
}