Skip to content

Commit 76bc804

Browse files
committed
fix(graphs): preserve multi-character vertices and use deque in traversals
1 parent 30507bb commit 76bc804

3 files changed

Lines changed: 51 additions & 63 deletions

File tree

‎graphs/breadth_first_search.py‎

Lines changed: 19 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -4,70 +4,33 @@
44

55
from __future__ import annotations
66

7-
from queue import Queue
7+
from collections import deque
8+
from collections.abc import Hashable
89

910

10-
class Graph:
11+
class Graph[Vertex: Hashable]:
1112
def __init__(self) -> None:
12-
self.vertices: dict[int, list[int]] = {}
13+
self.vertices: dict[Vertex, list[Vertex]] = {}
1314

14-
def print_graph(self) -> None:
15-
"""
16-
prints adjacency list representation of graaph
17-
>>> g = Graph()
18-
>>> g.print_graph()
19-
>>> g.add_edge(0, 1)
20-
>>> g.print_graph()
21-
0 : 1
22-
"""
23-
for i in self.vertices:
24-
print(i, " : ", " -> ".join([str(j) for j in self.vertices[i]]))
25-
26-
def add_edge(self, from_vertex: int, to_vertex: int) -> None:
27-
"""
28-
adding the edge between two vertices
29-
>>> g = Graph()
30-
>>> g.print_graph()
31-
>>> g.add_edge(0, 1)
32-
>>> g.print_graph()
33-
0 : 1
34-
"""
15+
def add_edge(self, from_vertex: Vertex, to_vertex: Vertex) -> None:
3516
if from_vertex in self.vertices:
3617
self.vertices[from_vertex].append(to_vertex)
3718
else:
3819
self.vertices[from_vertex] = [to_vertex]
3920

40-
def bfs(self, start_vertex: int) -> set[int]:
41-
"""
42-
>>> g = Graph()
43-
>>> g.add_edge(0, 1)
44-
>>> g.add_edge(0, 1)
45-
>>> g.add_edge(0, 2)
46-
>>> g.add_edge(1, 2)
47-
>>> g.add_edge(2, 0)
48-
>>> g.add_edge(2, 3)
49-
>>> g.add_edge(3, 3)
50-
>>> sorted(g.bfs(2))
51-
[0, 1, 2, 3]
52-
"""
53-
# initialize set for storing already visited vertices
54-
visited = set()
55-
56-
# create a first in first out queue to store all the vertices for BFS
57-
queue: Queue = Queue()
58-
59-
# mark the source node as visited and enqueue it
60-
visited.add(start_vertex)
61-
queue.put(start_vertex)
62-
63-
while not queue.empty():
64-
vertex = queue.get()
65-
66-
# loop through all adjacent vertex and enqueue it if not yet visited
67-
for adjacent_vertex in self.vertices[vertex]:
68-
if adjacent_vertex not in visited:
69-
queue.put(adjacent_vertex)
70-
visited.add(adjacent_vertex)
21+
def print_graph(self) -> None:
22+
for vertex, edges in self.vertices.items():
23+
print(f"{vertex} : {' -> '.join(map(str, edges))}")
24+
25+
def bfs(self, start_vertex: Vertex) -> set[Vertex]:
26+
visited: set[Vertex] = {start_vertex}
27+
queue: deque[Vertex] = deque([start_vertex])
28+
while queue:
29+
vertex = queue.popleft()
30+
for adjacent in self.vertices.get(vertex, []):
31+
if adjacent not in visited:
32+
visited.add(adjacent)
33+
queue.append(adjacent)
7134
return visited
7235

7336

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

7740
testmod(verbose=True)
7841

79-
g = Graph()
42+
g: Graph[int] = Graph()
8043
g.add_edge(0, 1)
8144
g.add_edge(0, 2)
8245
g.add_edge(1, 2)

‎graphs/depth_first_search.py‎

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,10 @@
22

33
from __future__ import annotations
44

5+
from collections.abc import Hashable
56

6-
def depth_first_search(graph: dict, start: str) -> set[str]:
7+
8+
def depth_first_search[Vertex: Hashable](graph: dict, start: Vertex) -> set[Vertex]:
79
"""Depth First Search on Graph
810
:param graph: directed graph in dictionary format
911
:param start: starting vertex as a string
@@ -17,16 +19,13 @@ def depth_first_search(graph: dict, start: str) -> set[str]:
1719
>>> all(x in output_G for x in list(depth_first_search(input_G, "G")))
1820
True
1921
"""
20-
explored, stack = set(start), [start]
21-
22+
explored: set[Vertex] = {start}
23+
stack: list[Vertex] = [start]
2224
while stack:
2325
v = stack.pop()
24-
explored.add(v)
25-
# Differences from BFS:
26-
# 1) pop last element instead of first one
27-
# 2) add adjacent elements to stack without exploring them
2826
for adj in reversed(graph[v]):
2927
if adj not in explored:
28+
explored.add(adj)
3029
stack.append(adj)
3130
return explored
3231

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
from collections.abc import Hashable
2+
3+
import pytest
4+
5+
from graphs.breadth_first_search import Graph as BfsGraph
6+
from graphs.depth_first_search import depth_first_search
7+
8+
9+
@pytest.mark.parametrize(
10+
("g", "s", "exp"),
11+
[
12+
({"root": ["leaf"], "leaf": []}, "root", {"root", "leaf"}),
13+
({10: [20], 20: []}, 10, {10, 20}),
14+
],
15+
)
16+
def test_dfs[Vertex: Hashable](
17+
g: dict[Vertex, list[Vertex]], s: Vertex, exp: set[Vertex]
18+
) -> None:
19+
assert depth_first_search(g, s) == exp
20+
21+
22+
def test_bfs_50k() -> None:
23+
bfs_graph: BfsGraph[int] = BfsGraph()
24+
for i in range(49_999):
25+
bfs_graph.add_edge(i, i + 1)
26+
assert len(bfs_graph.bfs(0)) == 50_000

0 commit comments

Comments
 (0)