0

I am trying to implement backtracking algorithm of finding a Hamiltonian Cycle - using stack instead of recursion, like in DFS. However, I can't figure out how to implement backtracking properly. The problem with my code is that at some point when there is no vertex to go to, instead of deleting the whole false path it keeps poping vertexes from the stack, and builds path incorrectly, ignoring, like, "levels" - number of available adjacent vertices, it goes for the previous level with previous set of vertices. There's another StackOverflow question with similar problem ("https://stackoverflow.com/questions/72594661/find-all-hamiltonian-cycles-using-bfs") - however there's no solution here. I've tried to implement the level approach - when if current level is invalid we step back - but failed. Any ideas? Help! Here is code, pseudo.

 bool HamiltonianCycle_It(vector<vector<int>>& G, vector<int> &path) {
        vector<bool> used(G.size(), false);
        stack<int> s;
        vector<int> level (G.size(), 0);
        int levelI = 0;
        s.push(0);
        while (!s.empty()) {
            int cr= s.top();
            s.pop();
            path.push_back(cr);
         
            if (path.size() == G.size()) {
                if (G[path[0]][ path[path.size() - 1]] == 1) {
                        path.push_back((path[0]));
                        return true;
                }
                path.pop_back();
                used[cr] = false;
                continue;
            }

            used[curr_vertex] = true;
            for (int i = 0; i < G.size(); i++) {
                if (G[cr][i] == 1 && used[i] == false) {
                    s.push(i);
                    level[levelI]++;

                }
            }
           if(level[levelI] == 0){
           level[levelI-1] --;
           levelI--;
           path.pop_back();
           used[cr] = false
              }
           else levelI++;

        
        }

        return false;
    }
};
Alex Ruby
  • 11
  • 1

0 Answers0