Shortest path (fewest nodes) for unweighted graph

后端 未结 5 949
猫巷女王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 20:09

    Thank you Giolekva!

    I rewrote it, refactoring some:

    • The collection of visited nodes doesn't have to be a map.
    • For path reconstruction, the next node could be looked up, instead of the previous node, eliminating the need for reversing the directions.
    public List getDirections(Node sourceNode, Node destinationNode) {
        //Initialization.
        Map nextNodeMap = new HashMap();
        Node currentNode = sourceNode;
    
        //Queue
        Queue queue = new LinkedList();
        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 visitedNodes = new HashSet();
        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 directions = new LinkedList();
        for (Node node = sourceNode; node != null; node = nextNodeMap.get(node)) {
            directions.add(node);
        }
    
        return directions;
    }
    

提交回复
热议问题