深度优先算法
深度优先算法
AristoreDepth First Search,一种优先走到底、无路可走再回头的遍历方式。
深度优先遍历的序列不唯一。相邻节点的遍历顺序允许被任意打乱。
测试图的结构
1 | graph1: |
实践
1 | from collections import deque |
流程图
graph TD Start["Start: Initialize visited, stack, and traversal_order"] --> A["Push the starting node onto stack"] A --> B["Check if stack is empty"] B -->|Stack is not empty| C["Pop the node from stack"] C --> D["Check if the node is in visited"] D -->|Not visited| E["Mark the node as visited"] E --> F["Append the node to traversal_order"] F --> G["Get neighbors of the node from graph[node]"] G --> H["Filter neighbors: Keep only unvisited neighbors"] H --> I["Push unvisited neighbors onto stack"] I --> B D -->|Already visited| B B -->|Stack is empty| End["End: Return traversal_order"] %% Subprocess for processing neighbors subgraph Loop["Neighbor Processing Logic"] G --> J["Iterate through each neighbor in graph[node]"] J --> K["Check if neighbor is in visited"] K -->|Not visited| L["Push the neighbor onto stack"] K -->|Already visited| M["Skip the neighbor"] L --> H M --> J end
评论
匿名评论隐私政策