-3
我在維基百科上爲什麼BFS算法使用隊列?
Breadth-First-Search(Graph, root):
2
3 for each node n in Graph:
4 n.distance = INFINITY
5 n.parent = NIL
6
7 create empty queue Q
8
9 root.distance = 0
10 Q.enqueue(root)
11
12 while Q is not empty:
13
14 current = Q.dequeue()
15
16 for each node n that is adjacent to current:
17 if n.distance == INFINITY:
18 n.distance = current.distance + 1
19 n.parent = current
20 Q.enqueue(n)
https://en.wikipedia.org/wiki/Breadth-first_search
看僞代碼和我很好奇的是,是否有就是爲什麼queueu用於保持節點具體原因。在我看來,可以使用任何容器,因爲通過容器中當前元素的順序是不相關的。
提示:如果是BFS,順序並非無關緊要。將它替換爲堆棧並猜測會發生什麼。 – Carcigenicate
另一個提示:考慮如果使用隊列或堆棧會發生什麼。 – Mai