-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathBFS
More file actions
125 lines (109 loc) · 2.2 KB
/
BFS
File metadata and controls
125 lines (109 loc) · 2.2 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
Breadth First Search(BFS) traversal
Detailed Explanation available here: https://youtu.be/6J50_2SD0C8
// C++
#include <iostream>
#include <queue>
using namespace std;
class Graph{
int m_V;
vector<vector<int>> m_adj;
public:
Graph(int V): m_V(V), m_adj(V){}
void addEdge(int u, int v){
m_adj[u].push_back(v);
}
void BFS(int s){
queue<int> Q;
vector<bool> visited(m_V, false);
Q.push(s);
visited[s] = true;
while(!Q.empty()){
int v = Q.front();
Q.pop();
cout << v << " ";
for(int u : m_adj[v])
if(!visited[u]){
Q.push(u);
visited[u] = true;
}
}
}
};
int main(){
Graph G(5);
G.addEdge(0,1);
G.addEdge(0,3);
G.addEdge(1,2);
G.addEdge(3,2);
G.addEdge(3,4);
G.BFS(0);
return 0;
}
// Java
import java.util.*;
import java.lang.*;
import java.io.*;
class Graph {
private int m_V;
private List<Integer>[] m_adj;
Graph(int v){
m_V = v;
m_adj = new LinkedList[v];
for(int i = 0; i < v; ++i)
m_adj[i] = new LinkedList<Integer>();
}
public void addEdge(int u, int v){
m_adj[u].add(v);
}
public void BFS(int s){
LinkedList<Integer> Q = new LinkedList();
boolean[] visited = new boolean[m_V];
Q.add(s);
visited[s] = true;
while(!Q.isEmpty()){
int v = Q.poll();
System.out.println(v+" ");
for(int u : m_adj[v]){
if(!visited[u]){
Q.add(u);
visited[u] = true;
}
}
}
}
public static void main (String[] args) throws java.lang.Exception{
Graph G = new Graph(5);
G.addEdge(0,1);
G.addEdge(0,3);
G.addEdge(1,2);
G.addEdge(3,2);
G.addEdge(3,4);
G.BFS(0);
}
}
# Python3
class Graph:
def __init__(self, v):
self.m_V = v
self.m_adj = [[] for i in range(v)]
def addEdge(self, u, v):
self.m_adj[u].append(v)
def BFS(self, s):
Q = []
visited = [False]*self.m_V
Q.append(s)
visited[s] = True
while len(Q) > 0:
v = Q.pop(0)
print(f'{v} ')
for u in self.m_adj[v]:
if not visited[u]:
Q.append(u)
visited[u] = True
G = Graph(5)
G.addEdge(0,1)
G.addEdge(0,3)
G.addEdge(1,2)
G.addEdge(3,2)
G.addEdge(3,4)
G.BFS(0)