Last active
February 24, 2024 04:05
-
-
Save devbruce/1fd538d406202c0594d3fedfdcd1153d to your computer and use it in GitHub Desktop.
DFS with recursive
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
__all__ = ['dfs_recursive'] | |
visited = set() | |
visited_orders = list() | |
def dfs_recursive(start_node: str, graph: dict[str, list[str]]) -> None: | |
if start_node in visited: | |
return | |
visited.add(start_node) | |
visited_orders.append(start_node) | |
adj_nodes = graph[start_node] | |
for node in adj_nodes: | |
dfs_recursive(node, graph) | |
if __name__ == '__main__': | |
import copy | |
GRAPH_INFO = r""" | |
[Graph] | |
A | |
/ \ | |
B C | |
/ \ / \ | |
D E F G | |
/|\ / \ | |
H I J K L | |
/\ | |
M N | |
* DFS Result: ["A", "B", "D", "H", "M", "N", "I", "J", "E", "C", "F", "G", "K", "L"] | |
* BFS Result: ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N"] | |
""" | |
GRAPH = { | |
"A": ["B", "C"], | |
"B": ["A", "D", "E"], | |
"C": ["A", "F", "G"], | |
"D": ["B", "H", "I", "J"], | |
"E": ["B"], | |
"F": ["C"], | |
"G": ["C", "K", "L"], | |
"H": ["D", "M", "N"], | |
"I": ["D"], | |
"J": ["D"], | |
"K": ["G"], | |
"L": ["G"], | |
"M": ["H"], | |
"N": ["H"], | |
} | |
print(GRAPH_INFO) | |
dfs_result = dfs_recursive(start_node="A", graph=copy.deepcopy(GRAPH)) | |
print(f"dfs: {visited_orders}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment