File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ from collections import deque
2+
3+ def bfs (graph , start ):
4+ # 初始化已訪問集合 (Visited Set),避免重複遍歷節點導致無窮迴圈
5+ visited = {start }
6+
7+ # 初始化雙端佇列 (Deque),並將起點放入佇列中作為 BFS 的起始點
8+ queue = deque ([start ])
9+
10+ # 當佇列中還有節點時,繼續搜尋
11+ while queue :
12+ # 從佇列左側取出最早進入的節點 (Popleft),實現 FIFO (First-In-First-Out)
13+ node = queue .popleft ()
14+
15+ # 輸出目前的節點
16+ print (node , end = " " )
17+
18+ # 遍歷目前節點的所有鄰居 (Neighbors)
19+ for neighbor in graph [node ]:
20+ # 如果該鄰居節點尚未被訪問過
21+ if neighbor not in visited :
22+ # 將其標記為已訪問 (Visited)
23+ visited .add (neighbor )
24+ # 將其加入佇列末端 (Append),排隊等待下一層搜尋
25+ queue .append (neighbor )
26+
27+ # 定義鄰接表 (Adjacency List),表示圖的結構
28+ graph = {
29+ 'A' : ['B' ,'C' ],
30+ 'B' : ['A' ,'D' ,'E' ],
31+ 'C' : ['A' ,'F' ],
32+ 'D' : ['B' ],
33+ 'E' : ['B' ,'F' ],
34+ 'F' : ['C' ,'E' ]
35+ }
36+
37+ # 從節點 'A' 開始執行廣度優先搜尋
38+ bfs (graph , 'A' )
39+ # 預期輸出: A B C D E F
Original file line number Diff line number Diff line change 1+ # Depth-First Search (DFS) - Iterative Approach(深度優先搜尋-迭代法)
2+ def dfs_iterative (graph , start ):
3+ # Initialize an empty set to keep track of visited nodes to avoid infinite loops
4+ visited = set ()
5+
6+ # Initialize a stack with the starting node
7+ stack = [start ]
8+
9+ # Continue searching as long as there are nodes in the stack
10+ while stack :
11+ # Remove and return the last element added to the stack (LIFO)
12+ node = stack .pop ()
13+
14+ # Check if the node has been visited before
15+ if node not in visited :
16+ # Print the current node (or perform other operations)
17+ print (node , end = " " )
18+
19+ # Mark the current node as visited
20+ visited .add (node )
21+
22+ # Add all unvisited neighbors of the current node to the stack
23+ # Note: The order in the stack determines the next node to visit
24+ stack .extend (graph [node ])
25+
26+ # Define the graph using an adjacency list
27+ graph = {
28+ 'A' : ['B' , 'C' ],
29+ 'B' : ['A' , 'D' , 'E' ],
30+ 'C' : ['A' , 'F' ],
31+ 'D' : ['B' ],
32+ 'E' : ['B' , 'F' ],
33+ 'F' : ['C' , 'E' ]
34+ }
35+
36+ # Execute the DFS starting from node 'A'
37+ # Output: A C F E B D
38+ dfs_iterative (graph , 'A' )
You can’t perform that action at this time.
0 commit comments