From 37fcf18ab21ee20c7ce2c958a53e8a7b3fc6628c Mon Sep 17 00:00:00 2001 From: LN18 Date: Sat, 28 Nov 2026 20:56:17 +1030 Subject: [PATCH] perf(graphs): replace recursive DFS with linear-time iterative deque --- graphs/depth_first_search.py | 39 +++++++++--------------------------- graphs/test_dfs_stress.py | 18 +++++++++++++++++ 2 files changed, 28 insertions(+), 29 deletions(-) create mode 100644 graphs/test_dfs_stress.py diff --git a/graphs/depth_first_search.py b/graphs/depth_first_search.py index a666e74ce607..58f29a5a29de 100644 --- a/graphs/depth_first_search.py +++ b/graphs/depth_first_search.py @@ -1,10 +1,11 @@ -"""Non recursive implementation of a DFS algorithm.""" +"""Iterative implementation of a Depth First Search algorithm.""" from __future__ import annotations -def depth_first_search(graph: dict, start: str) -> set[str]: +def depth_first_search(graph: dict[str, list[str]], start: str) -> set[str]: """Depth First Search on Graph + :param graph: directed graph in dictionary format :param start: starting vertex as a string :returns: the trace of the search @@ -17,32 +18,12 @@ 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[str] = {start} + stack: list[str] = [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: - stack.append(adj) + current = stack.pop() + for neighbor in graph.get(current, []): + if neighbor not in explored: + explored.add(neighbor) + stack.append(neighbor) return explored - - -G = { - "A": ["B", "C", "D"], - "B": ["A", "D", "E"], - "C": ["A", "F"], - "D": ["B", "D"], - "E": ["B", "F"], - "F": ["C", "E", "G"], - "G": ["F"], -} - -if __name__ == "__main__": - import doctest - - doctest.testmod() - print(depth_first_search(G, "A")) diff --git a/graphs/test_dfs_stress.py b/graphs/test_dfs_stress.py new file mode 100644 index 000000000000..e65d7949223e --- /dev/null +++ b/graphs/test_dfs_stress.py @@ -0,0 +1,18 @@ +import pytest + +from graphs.depth_first_search import depth_first_search + + +def build_linear_graph(node_count: int) -> dict[str, list[str]]: + graph: dict[str, list[str]] = {} + for i in range(node_count - 1): + graph[str(i)] = [str(i + 1)] + graph[str(node_count - 1)] = [] + return graph + + +@pytest.mark.parametrize("node_count", [100, 50000]) +def test_depth_first_search_large_linear_graph(node_count: int) -> None: + graph = build_linear_graph(node_count) + visited = depth_first_search(graph, "0") + assert len(visited) == node_count \ No newline at end of file