繁体   English   中英

未加权图的最短路径(最少节点)

[英]Shortest path (fewest nodes) for unweighted graph

我正在尝试构建一个方法,在未加权的图形中返回从一个节点到另一个节点的最短路径。 我考虑过使用Dijkstra,但这似乎有点矫枉过正,因为我只需要一对。 相反,我已经实现了广度优先搜索,但问题是我的返回列表包含一些我不想要的节点 - 如何修改我的代码以实现我的目标?

public List<Node> getDirections(Node start, Node finish){
    List<Node> directions = new LinkedList<Node>();
    Queue<Node> q = new LinkedList<Node>();
    Node current = start;
    q.add(current);
    while(!q.isEmpty()){
        current = q.remove();
        directions.add(current);
        if (current.equals(finish)){
            break;
        }else{
            for(Node node : current.getOutNodes()){
                if(!q.contains(node)){
                    q.add(node);
                }
            }
        }
    }
    if (!current.equals(finish)){
        System.out.println("can't reach destination");
    }
    return directions;
}

实际上你的代码不会在循环图中完成,考虑图1 - > 2 - > 1.你必须有一个数组,你可以标记你已经访问过哪个节点。 并且对于每个节点,您可以保存您来自的先前节点。 所以这里是正确的代码:

private Map<Node, Boolean>> vis = new HashMap<Node, Boolean>();

private Map<Node, Node> prev = new HashMap<Node, Node>();

public List getDirections(Node start, Node finish){
    List directions = new LinkedList();
    Queue q = new LinkedList();
    Node current = start;
    q.add(current);
    vis.put(current, true);
    while(!q.isEmpty()){
        current = q.remove();
        if (current.equals(finish)){
            break;
        }else{
            for(Node node : current.getOutNodes()){
                if(!vis.contains(node)){
                    q.add(node);
                    vis.put(node, true);
                    prev.put(node, current);
                }
            }
        }
    }
    if (!current.equals(finish)){
        System.out.println("can't reach destination");
    }
    for(Node node = finish; node != null; node = prev.get(node)) {
        directions.add(node);
    }
    directions.reverse();
    return directions;
}

谢谢Giolekva!

我重写了它,重构了一些:

  • 访问节点的集合不必是地图。
  • 对于路径重建,可以查找下一个节点,而不是前一个节点,从而无需反转方向。
public List<Node> getDirections(Node sourceNode, Node destinationNode) {
    //Initialization.
    Map<Node, Node> nextNodeMap = new HashMap<Node, Node>();
    Node currentNode = sourceNode;

    //Queue
    Queue<Node> queue = new LinkedList<Node>();
    queue.add(currentNode);

    /*
     * The set of visited nodes doesn't have to be a Map, and, since order
     * is not important, an ordered collection is not needed. HashSet is 
     * fast for add and lookup, if configured properly.
     */
    Set<Node> visitedNodes = new HashSet<Node>();
    visitedNodes.add(currentNode);

    //Search.
    while (!queue.isEmpty()) {
        currentNode = queue.remove();
        if (currentNode.equals(destinationNode)) {
            break;
        } else {
            for (Node nextNode : getChildNodes(currentNode)) {
                if (!visitedNodes.contains(nextNode)) {
                    queue.add(nextNode);
                    visitedNodes.add(nextNode);

                    //Look up of next node instead of previous.
                    nextNodeMap.put(currentNode, nextNode);
                }
            }
        }
    }

    //If all nodes are explored and the destination node hasn't been found.
    if (!currentNode.equals(destinationNode)) {
        throw new RuntimeException("No feasible path.");
    }

    //Reconstruct path. No need to reverse.
    List<Node> directions = new LinkedList<Node>();
    for (Node node = sourceNode; node != null; node = nextNodeMap.get(node)) {
        directions.add(node);
    }

    return directions;
}

得到一对的答案比对所有对都简单得多。 计算最短路径的常用方法是像您一样开始,但只要遇到新节点并在路径上记录上一个节点就做一个注释。 然后,当您到达目标节点时,您可以跟踪到源的反向链接并获取路径。 因此,从循环中删除directions.add(current) ,并添加类似以下内容的代码

Map<Node,Node> backlinks = new HashMap<Node,Node>();

在开始然后在循环中

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

然后最后,使用backlinks映射向后构建directions列表。

每次通过循环,你都会打电话

directions.Add(current);

相反,你应该把它移到你真正知道你想要那个条目的地方。

将它们放入队列时,必须将父节点包含在每个节点中。 然后,您可以递归地从该列表中读取路径。

假设您要在此图中找到从A到D的最短路径:

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

每次排队节点时,都要跟踪到达此处的方式。 因此,在步骤1 B(A)中,E(A)被放在队列中。 在第二步中B出队并且C(B)被放入队列等。然后通过“向后”递归,它很容易找到回来的路。

最好的方法可能是制作一个数组,只要有节点并保持链接在那里(这通常是在Dijkstra's中完成的)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM