mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-11-24 13:31:07 +00:00
bc8df6de31
* [pre-commit.ci] pre-commit autoupdate updates: - [github.com/astral-sh/ruff-pre-commit: v0.2.2 → v0.3.2](https://github.com/astral-sh/ruff-pre-commit/compare/v0.2.2...v0.3.2) - [github.com/pre-commit/mirrors-mypy: v1.8.0 → v1.9.0](https://github.com/pre-commit/mirrors-mypy/compare/v1.8.0...v1.9.0) * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
49 lines
1.4 KiB
Python
49 lines
1.4 KiB
Python
"""Non recursive implementation of a DFS algorithm."""
|
|
|
|
from __future__ import annotations
|
|
|
|
|
|
def depth_first_search(graph: dict, 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
|
|
>>> input_G = { "A": ["B", "C", "D"], "B": ["A", "D", "E"],
|
|
... "C": ["A", "F"], "D": ["B", "D"], "E": ["B", "F"],
|
|
... "F": ["C", "E", "G"], "G": ["F"] }
|
|
>>> output_G = list({'A', 'B', 'C', 'D', 'E', 'F', 'G'})
|
|
>>> all(x in output_G for x in list(depth_first_search(input_G, "A")))
|
|
True
|
|
>>> all(x in output_G for x in list(depth_first_search(input_G, "G")))
|
|
True
|
|
"""
|
|
explored, stack = set(start), [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)
|
|
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"))
|