2016-09-27 133 views
-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用於保持節點具體原因。在我看來,可以使用任何容器,因爲通過容器中當前元素的順序是不相關的。

+1

提示:如果是BFS,順序並非無關緊要。將它替換爲堆棧並猜測會發生什麼。 – Carcigenicate

+0

另一個提示:考慮如果使用隊列或堆棧會發生什麼。 – Mai

回答

0

隊列不僅是一個容器。這正是這種算法的關鍵思想。

隊列是 1.一個容器肯定。 2.它只能按特定順序添加/彈出(隊列和堆棧都具有此屬性)

第二點是回答您的問題的關鍵點。

如果您使用隊列作爲通用列表,直接通過列表索引添加和彈出元素,整個算法就不會那麼簡單。 (即隊列不再是隊列)