Skip to content

update graphs/breadth_first_search.py #3908

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Dec 9, 2020
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 20 additions & 18 deletions graphs/breadth_first_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,33 +2,35 @@

""" Author: OMKAR PATHAK """

from typing import Set


class Graph:
def __init__(self):
self.vertices = {}

def printGraph(self):
def print_graph(self) -> None:
"""prints adjacency list representation of graaph"""
for i in self.vertices.keys():
for i in self.vertices:
print(i, " : ", " -> ".join([str(j) for j in self.vertices[i]]))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

print(i, " : ", " -> ".join([str(j) for j in self.vertices[i]]))

edit to

print(i, " : ", " -> ".join(str(j) for j in self.vertices[i]))


def addEdge(self, fromVertex, toVertex):
def add_edge(self, from_vertex: int, to_vertex: int) -> None:
"""adding the edge between two vertices"""
if fromVertex in self.vertices.keys():
self.vertices[fromVertex].append(toVertex)
if from_vertex in self.vertices:
self.vertices[from_vertex].append(to_vertex)
else:
self.vertices[fromVertex] = [toVertex]
self.vertices[from_vertex] = [to_vertex]

def BFS(self, startVertex):
def bfs(self, start_vertex: int) -> Set[int]:
# initialize set for storing already visited vertices
visited = set()

# create a first in first out queue to store all the vertices for BFS
queue = []

# mark the source node as visited and enqueue it
visited.add(startVertex)
queue.append(startVertex)
visited.add(start_vertex)
queue.append(start_vertex)

while queue:
vertex = queue.pop(0)
Expand All @@ -43,17 +45,17 @@ def BFS(self, startVertex):

if __name__ == "__main__":
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

add

from doctest import testmod
testmod()

g = Graph()
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3)
g.addEdge(3, 3)

g.printGraph()
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(1, 2)
g.add_edge(2, 0)
g.add_edge(2, 3)
g.add_edge(3, 3)

g.print_graph()
# 0 : 1 -> 2
# 1 : 2
# 2 : 0 -> 3
# 3 : 3

assert sorted(g.BFS(2)) == [0, 1, 2, 3]
assert sorted(g.bfs(2)) == [0, 1, 2, 3]