2020-09-11 14:23:26 +00:00
|
|
|
"""Non recursive implementation of a DFS algorithm."""
|
|
|
|
|
2020-09-23 11:30:13 +00:00
|
|
|
from __future__ import annotations
|
2020-04-17 18:05:29 +00:00
|
|
|
|
2021-06-10 17:06:41 +00:00
|
|
|
from typing import Set
|
2020-04-17 18:05:29 +00:00
|
|
|
|
2021-06-10 17:06:41 +00:00
|
|
|
|
|
|
|
def depth_first_search(graph: dict, start: str) -> Set[str]:
|
2020-04-17 18:05:29 +00:00
|
|
|
"""Depth First Search on Graph
|
2020-09-10 08:31:26 +00:00
|
|
|
:param graph: directed graph in dictionary format
|
2021-06-10 17:06:41 +00:00
|
|
|
:param start: starting vertex as a string
|
2020-09-10 08:31:26 +00:00
|
|
|
:returns: the trace of the search
|
2021-06-10 17:06:41 +00:00
|
|
|
>>> input_G = { "A": ["B", "C", "D"], "B": ["A", "D", "E"],
|
2020-09-10 08:31:26 +00:00
|
|
|
... "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'})
|
2021-06-10 17:06:41 +00:00
|
|
|
>>> all(x in output_G for x in list(depth_first_search(input_G, "A")))
|
2020-09-10 08:31:26 +00:00
|
|
|
True
|
2021-06-10 17:06:41 +00:00
|
|
|
>>> all(x in output_G for x in list(depth_first_search(input_G, "G")))
|
2020-09-10 08:31:26 +00:00
|
|
|
True
|
2020-04-17 18:05:29 +00:00
|
|
|
"""
|
|
|
|
explored, stack = set(start), [start]
|
2020-09-11 14:23:26 +00:00
|
|
|
|
2020-04-17 18:05:29 +00:00
|
|
|
while stack:
|
|
|
|
v = stack.pop()
|
2020-09-11 14:23:26 +00:00
|
|
|
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)
|
2020-04-17 18:05:29 +00:00
|
|
|
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"],
|
|
|
|
}
|
2019-10-05 05:14:13 +00:00
|
|
|
|
|
|
|
if __name__ == "__main__":
|
2020-04-17 18:05:29 +00:00
|
|
|
import doctest
|
2018-10-19 12:48:28 +00:00
|
|
|
|
2020-04-17 18:05:29 +00:00
|
|
|
doctest.testmod()
|
|
|
|
print(depth_first_search(G, "A"))
|