algorithm - Time complexity for hamiltonian path -
algorithm - Time complexity for hamiltonian path -
below code find if hamiltonian path exist in graph using backtracking. , per code below time complexity comes out o(v^2)
, v
total number vertices. hamiltonian problem np-complete. per understanding, problem cannot solved in polynomial time n^k
, n
input , k
constant. have tested code below , working fine. did calculate time complexity wrong ?
public boolean check() { stack<node> nodestack = new stack<>(); nodestack.add(root); root.setisonstack(); while (!nodestack.isempty()) { node currentnode = nodestack.peek(); (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) { homecoming true; } } if (currentnode == nodestack.peek()) { (entry<node, boolean> entry : currentnode.getneighbourlist().entryset()) { currentnode.setnodeisnotvisited(entry.getkey()); } nodestack.pop(); currentnode.setisnotonstack(); node nodeontop = nodestack.peek(); nodeontop.setnodeisvisited(currentnode); } } homecoming 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() { homecoming label; } public void addneighbour(node node) { neighbourlist.put(node, false); } public boolean isonstack() { homecoming isonstack; } public void setisonstack() { isonstack = true; } public void setisnotonstack() { isonstack = false; } public map<node, boolean> getneighbourlist() { homecoming neighbourlist; } public void setnodeisvisited(node node) { neighbourlist.replace(node, true); } public void setnodeisnotvisited(node node) { neighbourlist.replace(node, false); } public boolean isnodevisited(node node) { homecoming neighbourlist.get(node); } }
algorithm time-complexity graph-algorithm np hamiltonian-cycle
Comments
Post a Comment