diff --git a/graphs/breadth_first_search.py b/graphs/breadth_first_search.py index cab79be39ed3..9b721327eb22 100644 --- a/graphs/breadth_first_search.py +++ b/graphs/breadth_first_search.py @@ -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]])) - - 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 print_graph(self) -> None: + for vertex, edges in self.vertices.items(): + print(f"{vertex} : {' -> '.join(map(str, edges))}") + + 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 @@ -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) diff --git a/graphs/depth_first_search.py b/graphs/depth_first_search.py index a666e74ce607..d3a840628337 100644 --- a/graphs/depth_first_search.py +++ b/graphs/depth_first_search.py @@ -2,8 +2,10 @@ 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, start: Vertex) -> set[Vertex]: """Depth First Search on Graph :param graph: directed graph in dictionary format :param start: starting vertex as a string @@ -17,16 +19,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 diff --git a/graphs/test_graph_traversal_regression.py b/graphs/test_graph_traversal_regression.py new file mode 100644 index 000000000000..afece181d464 --- /dev/null +++ b/graphs/test_graph_traversal_regression.py @@ -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