Shortest path (fewest nodes) for unweighted graph

后端 未结 5 928
猫巷女王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条回答
  •  粉色の甜心
    2020-12-07 19:56

    It is really no simpler to get the answer for just one pair than for all the pairs. The usual way to calculate a shortest path is to start like you do, but make a note whenever you encounter a new node and record the previous node on the path. Then, when you reach the target node, you can follow the backlinks to the source and get the path. So, remove the directions.add(current) from the loop, and add code something like the following

    Map backlinks = new HashMap();
    

    in the beginning and then in the loop

    if (!backlinks.containsKey(node)) {
        backlinks.add(node, current);
        q.add(node);
    }
    

    and then in the end, just construct the directions list in backwards using the backlinks map.

提交回复
热议问题