Shortest path (fewest nodes) for unweighted graph

后端 未结 5 938
猫巷女王i
猫巷女王i 2020-12-07 19:34

I\'m trying build a method which returns the shortest path from one node to another in an unweighted graph. I considered the use of Dijkstra\'s but this seems a bit overkil

5条回答
  •  萌比男神i
    2020-12-07 20:10

    You must include the parent node to each node when you put them on your queue. Then you can just recursively read the path from that list.

    Say you want to find the shortest path from A to D in this Graph:

         /B------C------D
       /                |
     A                 /
       \             /
         \E---------
    

    Each time you enqueue a node, keep track of the way you got here. So in step 1 B(A) E(A) is put on the queue. In step two B gets dequeued and C(B) is put on the queue etc. Its then easy to find your way back again, by just recursing "backwards".

    Best way is probably to make an array as long as there are nodes and keep the links there, (which is whats usually done in ie. Dijkstra's).

提交回复
热议问题