Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
71 changes: 17 additions & 54 deletions graphs/breadth_first_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,70 +4,33 @@

from __future__ import annotations

from queue import Queue
from collections import deque
from collections.abc import Hashable


class Graph:
class Graph[Vertex: Hashable]:
def __init__(self) -> None:
self.vertices: dict[int, list[int]] = {}
self.vertices: dict[Vertex, list[Vertex]] = {}

def print_graph(self) -> None:
"""
prints adjacency list representation of graaph
>>> g = Graph()
>>> g.print_graph()
>>> g.add_edge(0, 1)
>>> g.print_graph()
0 : 1
"""
for i in self.vertices:
print(i, " : ", " -> ".join([str(j) for j in self.vertices[i]]))
for vertex, edges in self.vertices.items():
print(f"{vertex} : {' -> '.join(map(str, edges))}")

def add_edge(self, from_vertex: int, to_vertex: int) -> None:
"""
adding the edge between two vertices
>>> g = Graph()
>>> g.print_graph()
>>> g.add_edge(0, 1)
>>> g.print_graph()
0 : 1
"""
def add_edge(self, from_vertex: Vertex, to_vertex: Vertex) -> None:
if from_vertex in self.vertices:
self.vertices[from_vertex].append(to_vertex)
else:
self.vertices[from_vertex] = [to_vertex]

def bfs(self, start_vertex: int) -> set[int]:
"""
>>> g = Graph()
>>> g.add_edge(0, 1)
>>> 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)
>>> sorted(g.bfs(2))
[0, 1, 2, 3]
"""
# initialize set for storing already visited vertices
visited = set()

# create a first in first out queue to store all the vertices for BFS
queue: Queue = Queue()

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

while not queue.empty():
vertex = queue.get()

# loop through all adjacent vertex and enqueue it if not yet visited
for adjacent_vertex in self.vertices[vertex]:
if adjacent_vertex not in visited:
queue.put(adjacent_vertex)
visited.add(adjacent_vertex)
def bfs(self, start_vertex: Vertex) -> set[Vertex]:
visited: set[Vertex] = {start_vertex}
queue: deque[Vertex] = deque([start_vertex])
while queue:
vertex = queue.popleft()
for adjacent in self.vertices.get(vertex, []):
if adjacent not in visited:
visited.add(adjacent)
queue.append(adjacent)
return visited


Expand All @@ -76,7 +39,7 @@ def bfs(self, start_vertex: int) -> set[int]:

testmod(verbose=True)

g = Graph()
g: Graph[int] = Graph()
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(1, 2)
Expand Down
15 changes: 8 additions & 7 deletions graphs/depth_first_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,12 @@

from __future__ import annotations

from collections.abc import Hashable

def depth_first_search(graph: dict, start: str) -> set[str]:

def depth_first_search[Vertex: Hashable](
graph: dict[Vertex, list[Vertex]], start: Vertex
) -> set[Vertex]:
"""Depth First Search on Graph
:param graph: directed graph in dictionary format
:param start: starting vertex as a string
Expand All @@ -17,16 +21,13 @@ def depth_first_search(graph: dict, start: str) -> set[str]:
>>> all(x in output_G for x in list(depth_first_search(input_G, "G")))
True
"""
explored, stack = set(start), [start]

explored: set[Vertex] = {start}
stack: list[Vertex] = [start]
while stack:
v = stack.pop()
explored.add(v)
# Differences from BFS:
# 1) pop last element instead of first one
# 2) add adjacent elements to stack without exploring them
for adj in reversed(graph[v]):
if adj not in explored:
explored.add(adj)
stack.append(adj)
return explored

Expand Down
26 changes: 26 additions & 0 deletions graphs/test_graph_traversal_regression.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
from collections.abc import Hashable

import pytest

from graphs.breadth_first_search import Graph as BfsGraph
from graphs.depth_first_search import depth_first_search


@pytest.mark.parametrize(
("g", "s", "exp"),
[
({"root": ["leaf"], "leaf": []}, "root", {"root", "leaf"}),
({10: [20], 20: []}, 10, {10, 20}),
],
)
def test_dfs[Vertex: Hashable](
g: dict[Vertex, list[Vertex]], s: Vertex, exp: set[Vertex]
) -> None:
assert depth_first_search(g, s) == exp


def test_bfs_50k() -> None:
bfs_graph: BfsGraph[int] = BfsGraph()
for i in range(49_999):
bfs_graph.add_edge(i, i + 1)
assert len(bfs_graph.bfs(0)) == 50_000
Loading