0

below is the code to find if a Hamiltonian path exist in a graph using backtracking. And as per the code below time complexity comes out to be O(V^2), where V is total number to vertices. But Hamiltonian problem is NP-Complete. which as per my understanding, a problem that cannot be solved in polynomial time n^k, where n is input and k is some constant. I have tested the code below and is working fine. So did I calculate time complexity wrong ?

 public boolean check() {

    Stack<Node> nodeStack = new Stack<>();
    nodeStack.add(root);
    root.setIsOnStack();

    while (!nodeStack.isEmpty()) {  

        Node currentNode = nodeStack.peek();   
        for (Entry<Node, Boolean> entry : currentNode.getNeighbourList().entrySet()) { 
            Node currentNeighbourer = entry.getKey();
            if (!currentNeighbourer.isOnStack()) { 
                if (!entry.getValue()) {  
                    nodeStack.push(currentNeighbourer); 
                    currentNeighbourer.setIsOnStack();
                    break;
                }
            } else if (currentNeighbourer == root && nodeStack.size() == noOfVertices) {  
                return true;
            }
        }
        if (currentNode == nodeStack.peek()) {
            for (Entry<Node, Boolean> entry : currentNode.getNeighbourList().entrySet()) { 
                currentNode.setNodeIsNotVisited(entry.getKey()); 
            }
            nodeStack.pop();
            currentNode.setIsNotOnStack();
            Node nodeOnTop = nodeStack.peek();
            nodeOnTop.setNodeIsVisited(currentNode);
        }
    }
    return false;
}

Node class:

  public class Node {

private final char label;
private Map<Node, Boolean> neighbourList;
private boolean isOnStack;

public Node(char label) {
    this.label = label;
    this.isOnStack = false;
    neighbourList = new LinkedHashMap<>();
}

public char getLabel() {
    return label;
}

public void addNeighbour(Node node) {
    neighbourList.put(node, false);
}

public boolean isOnStack() {
    return isOnStack;
}

public void setIsOnStack() {
    isOnStack = true;
}

public void setIsNotOnStack() {
    isOnStack = false;
}

public Map<Node, Boolean> getNeighbourList() {
    return neighbourList;
}

public void setNodeIsVisited(Node node) {
    neighbourList.replace(node, true);        
}

public void setNodeIsNotVisited(Node node) {
    neighbourList.replace(node, false);        
}

public boolean isNodeVisited(Node node) {
    return neighbourList.get(node);
}

}
Meena Chaudhary
  • 9,909
  • 16
  • 60
  • 94
  • tell us, why would you think its O(V^2)? How large were your testcases? what is the output for testcases where no hamilton path exists? As far as i can see its a typical O(V^V) algorithm – Terry Storm Oct 24 '14 at 21:24
  • btw backtracking is usually no approach to achieve polynomial time algorithms (except if u prune some branches that way) – Terry Storm Oct 24 '14 at 21:32

0 Answers0