使用BFS解决这样的未加权图中的最短路径问题。
伪代码:
Create Queue q;
push into q starting node and mark distance to starting node as 0.
while(q is not empty){
get n : first elemnt in the queue
get all connected nodes to n that are not yet visited and push them to the queue:
mark the distance to those node as the distance to n + 1.
}
示例:假设您的起始节点是 1。
您在图中的连接:
1->2, 1->3, 1->4
2->1, 2->3, 2->4
3->1, 3->2, 3->4
设置一个访问过的布尔数组:visited 4 = {false,false,false,false},距离数组 dist 4 = {inf,inf,inf,inf} 和父数组 = {-1,-1,-1, -1}。
现在将节点 1 推入队列 Q,将其距离设置为 0,将父节点设置为 1,然后开始:
迭代 1 状态:
Queue = {1}
Dist = {0,inf,inf,inf}
visited= {true,false,false,false}
parent= {1,-1,-1,-1}
迭代 2:
队列中唯一的节点是 1,您选择它并将它们的邻居推送到队列中,它们是节点:2、3、4。更新他们的距离
Queue = {2,3,4}
Dist = {0,1,1,1}
visited= {true,false,false,false}
parent= {1,1,1,1}
依此类推,直到你得到一个空队列。(意味着您已经访问了所有节点)。
在这个例子中,你会看到到节点 3 的距离是 Dist 3 = 1,这个节点的父节点是 parent 3 = 1(如果你想重建路径)。
有关更多信息,请检查BFS以及 Python 中的实现:Python BFS DFS或此