Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 0cba10d

Browse files
Create Graph-BFS
Breadth-First Search in Graphs using the algorithm learnt from MIT 6.006 BFS lecture. Simple Implementation takes O(V+E) time because we are only visiting every edge/vertex once thus, we can also tighten it to saying O(E) according to Erik Demaine, professor MIT.
1 parent 7769fe0 commit 0cba10d

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

‎Graph-BFS

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
def bfs(g,N):
2+
'''
3+
:param g: given adjacency list of graph
4+
:param N: number of nodes in N.
5+
'''
6+
# code here
7+
# level determines the cost/steps to reach specific node from start node
8+
# level where a vertex is located from the initial considered vertex
9+
level = {0:0}
10+
# parent stores the path to vertices, to determine the edges
11+
# we can also caculate the shortest path taken by accessing the parent
12+
# of specific vertex(value of that vertex(key)), again checking
13+
# value/parent of the previous parent vertex.
14+
# assume: v <- c
15+
# c <- x
16+
# x <- s
17+
# s <- None
18+
# until we get None/specific assumed parent vertex
19+
# refer MIT lecture video BFS 6.006
20+
parent = {0:None}
21+
# first level 0 is already set, the intial/start vertex 0
22+
# so now moving towards i = 1 and exploring other levels accessible
23+
# to that initial/start vertex
24+
i = 1
25+
# a list storing the vertices we have to currently explore
26+
frontier = [0]
27+
print(frontier[0], end=' ')
28+
while frontier:
29+
# next_ stores the edge nodes that are to be explored for each vertex
30+
next_ = []
31+
# Below for loop iterates over vertices present in the Adjacency List
32+
for u in frontier:
33+
# Below for loop iterates over the edges/neighbouring vertices
34+
for v in g[u]:
35+
# avoids duplicacy of vertices, thus, avoiding duplicate
36+
# edges and cycling of graph
37+
if v not in level:
38+
level[v] = i
39+
parent[v] = u
40+
next_.append(v)
41+
print(v, end=' ')
42+
frontier = next_
43+
i += 1

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /