mirror of
https://github.com/krahets/hello-algo.git
synced 2026-02-03 10:53:35 +08:00
* Review the EN heading format. * Fix pythontutor headings. * Fix pythontutor headings. * bug fixes * Fix headings in **/summary.md * Revisit the CN-to-EN translation for Python code using Claude-4.5 * Revisit the CN-to-EN translation for Java code using Claude-4.5 * Revisit the CN-to-EN translation for Cpp code using Claude-4.5. * Fix the dictionary. * Fix cpp code translation for the multipart strings. * Translate Go code to English. * Update workflows to test EN code. * Add EN translation for C. * Add EN translation for CSharp. * Add EN translation for Swift. * Trigger the CI check. * Revert. * Update en/hash_map.md * Add the EN version of Dart code. * Add the EN version of Kotlin code. * Add missing code files. * Add the EN version of JavaScript code. * Add the EN version of TypeScript code. * Fix the workflows. * Add the EN version of Ruby code. * Add the EN version of Rust code. * Update the CI check for the English version code. * Update Python CI check. * Fix cmakelists for en/C code. * Fix Ruby comments
58 lines
1.7 KiB
Python
58 lines
1.7 KiB
Python
"""
|
|
File: graph_dfs.py
|
|
Created Time: 2023-02-23
|
|
Author: krahets (krahets@163.com)
|
|
"""
|
|
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
sys.path.append(str(Path(__file__).parent.parent))
|
|
from modules import Vertex, vets_to_vals, vals_to_vets
|
|
from graph_adjacency_list import GraphAdjList
|
|
|
|
|
|
def dfs(graph: GraphAdjList, visited: set[Vertex], res: list[Vertex], vet: Vertex):
|
|
"""Depth-first traversal helper function"""
|
|
res.append(vet) # Record visited vertex
|
|
visited.add(vet) # Mark this vertex as visited
|
|
# Traverse all adjacent vertices of this vertex
|
|
for adjVet in graph.adj_list[vet]:
|
|
if adjVet in visited:
|
|
continue # Skip vertices that have been visited
|
|
# Recursively visit adjacent vertices
|
|
dfs(graph, visited, res, adjVet)
|
|
|
|
|
|
def graph_dfs(graph: GraphAdjList, start_vet: Vertex) -> list[Vertex]:
|
|
"""Depth-first traversal"""
|
|
# Use adjacency list to represent the graph, in order to obtain all adjacent vertices of a specified vertex
|
|
# Vertex traversal sequence
|
|
res = []
|
|
# Hash set for recording vertices that have been visited
|
|
visited = set[Vertex]()
|
|
dfs(graph, visited, res, start_vet)
|
|
return res
|
|
|
|
|
|
"""Driver Code"""
|
|
if __name__ == "__main__":
|
|
# Initialize undirected graph
|
|
v = vals_to_vets([0, 1, 2, 3, 4, 5, 6])
|
|
edges = [
|
|
[v[0], v[1]],
|
|
[v[0], v[3]],
|
|
[v[1], v[2]],
|
|
[v[2], v[5]],
|
|
[v[4], v[5]],
|
|
[v[5], v[6]],
|
|
]
|
|
graph = GraphAdjList(edges)
|
|
print("\nAfter initialization, the graph is")
|
|
graph.print()
|
|
|
|
# Depth-first traversal
|
|
res = graph_dfs(graph, v[0])
|
|
print("\nDepth-first traversal (DFS) vertex sequence is")
|
|
print(vets_to_vals(res))
|