Wikipedia's pseudocode for Breadth-first search: How could n's parent be u if “n is adjacent to u”?

生来就可爱ヽ(ⅴ<●) 提交于 2020-02-08 02:23:41

问题


Studying the Breadth-first search algorithm, I encountered the following pseudo-code:

 1 Breadth-First-Search(G, v):
 2 
 3     for each node n in G:            
 4         n.distance = INFINITY        
 5         n.parent = NIL
 6 
 7     create empty queue Q      
 8 
 9     v.distance = 0
10     Q.enqueue(v)                      
11 
12     while Q is not empty:        
13     
14         u = Q.dequeue()
15     
16         for each node n that is adjacent to u:
17             if n.distance == INFINITY:
18                 n.distance = u.distance + 1
19                 n.parent = u
20                 Q.enqueue(n)

My question is regarding line 19 (n.parent = u):

How could n's parent be u if "n is adjacent to u"?


回答1:


A parent is by definition adjacent to its children, they wouldn't be children without the connection. But that's not what this is about. The parent pointers are something completely separate from the structure of the graph, it's something new you're building up that keeps track of from where a node was first reached.



来源:https://stackoverflow.com/questions/33802704/wikipedias-pseudocode-for-breadth-first-search-how-could-ns-parent-be-u-if-n

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!