Finding the shortest path nodes with breadth first search

前端 未结 3 962
轮回少年
轮回少年 2020-12-10 17:02

I am running breadth first search on the above graph to find the shortest path from Node 0 to Node 6.

My code

pu         


        
3条回答
  •  囚心锁ツ
    2020-12-10 17:29

    In addition to the already given answer by user3290797.

    It looks like You are dealing with an unweighted graph. We interpret this as every edge has a weight of 1. In this case, once You have associated a distance to the root node with every node of the graph (the breadth-first traversal), it becomes trivial to reconstruct the shortest path from any node, and even detect if there are multiple ones.

    All You need to do is a breadth- (in case You want every shortest path) or depth-first traversal of the same graph starting from the target node and only considering neighbours with a depth's value of exactly 1 less.

    So we need to jump from distance 4 (node 6) to 3, 2, 1, 0, and there is only one way (in this case) to do so.

    In case we are interested in the shortest path to node 4 the result would be distances 2-1-0 or nodes 4-3-0 or 4-8-0.

    BTW, this approach can easily be modified to work with weighted graphs (with non-negative weights) too: valid neighbours are those with distance equals to current minus the weight of the edge -- this involves some actual calculations and directly storing previous nodes along the shortest path might be better.

提交回复
热议问题