Related Articles

# Print all Hamiltonian Cycles in an Undirected Graph

• Difficulty Level : Easy
• Last Updated : 15 Jun, 2021

Given an undirected Graph consisting of N nodes in the form of an adjacency matrix graph[][] of size N*N, the task is to print all Hamiltonian cycles possible in the given undirected Graph (taking starting vertex as ‘0’).

A Hamiltonian cycle (or Hamiltonian circuit) is a Hamiltonian Path such that there is an edge (in the graph) from the last vertex to the first vertex of the Hamiltonian Path.

Examples:

Input: graph[][] = {{0, 1, 1, 0, 0, 1}, {1, 0, 1, 0, 1, 1}, {1, 1, 0, 1, 0, 0}, {0, 0, 1, 0, 1, 0}, {0, 1, 0, 1, 0, 1}, {1, 1, 0, 0, 1, 0}}
Output:
0 1 2 3 4 5 0
0 1 5 4 3 2 0
0 2 3 4 1 5 0
0 2 3 4 5 1 0
0 5 1 4 3 2 0
0 5 4 3 2 1 0
Explanation:
All Possible Hamiltonian Cycles for the following graph (with the starting vertex as 0) are

1. {0 → 1 → 2 → 3 → 4 → 5 → 0}
2. {0 → 1 → 5 → 4 → 3 → 2 → 0}
3. {0 → 2 → 3 → 4 → 1 → 5 → 0}
4. {0 → 2 → 3 → 4 → 5 → 1 → 0}
5. {0 → 5 → 1 → 4 → 3 → 2 → 0}
6. {0 → 5 → 4 → 3 → 2 → 1 → 0}

Input: graph[][] = {{0, 1, 0, 1, 1, 0, 0}, {1, 0, 1, 0, 0, 0, 0}, {0, 1, 0, 1, 0, 0, 1}, {1, 0, 1, 0, 0, 1, 0}, {1, 0, 0, 0, 0, 1, 0}, {0, 0, 0, 1, 1, 0, 1}, {0, 0, 1, 0, 0, 1, 0}}
Output: No Hamiltonian Cycle possible
Explanation:
For the given graph, no Hamiltonian Cycle is possible:

Approach: The given problem can be solved by using Backtracking to generate all possible Hamiltonian Cycles. Follow the steps below to solve the problem:

• Create an auxiliary array, say path[] to store the order of traversal of nodes and a boolean array visited[] to keep track of vertices included in the current path.
• Initially, add the source vertex (in this case ‘0’) to the path.
• Now, recursively add vertices to path one by one to find the cycle.
• Before adding a vertex to path, check whether the vertex being considered is adjacent to the previously added vertex or not and is not already in path. If such a vertex is found, then add it to the path and mark its value as true in the visited[] array.
• If the length of path becomes equal to N, and there is an edge from the last vertex in path to 0, then print the path array.
• After completing the above steps, if there exists no such path, then print No Hamiltonian Cycle possible.

Below is the implementation of the above approach:

## Java

 `// Java program for the above approach`` ` `import` `java.util.ArrayList;``class` `GFG {`` ` `    ``// Function to check if a vertex v``    ``// can be added at index pos in``    ``// the Hamiltonian Cycle``    ``boolean` `isSafe(``int` `v, ``int` `graph[][],``                   ``ArrayList path,``                   ``int` `pos)``    ``{``        ``// If the vertex is adjacent to``        ``// the vertex of the previously``        ``// added vertex``        ``if` `(graph[path.get(pos - ``1``)][v]``            ``== ``0``)``            ``return` `false``;`` ` `        ``// If the vertex has already``        ``// been included in the path``        ``for` `(``int` `i = ``0``; i < pos; i++)``            ``if` `(path.get(i) == v)``                ``return` `false``;`` ` `        ``// Both the above conditions are``        ``// not true, return true``        ``return` `true``;``    ``}`` ` `    ``// To check if there exists``    ``// at least 1 hamiltonian cycle``    ``boolean` `hasCycle;`` ` `    ``// Function to find all possible``    ``// hamiltonian cycles``    ``void` `hamCycle(``int` `graph[][])``    ``{``        ``// Initially value of boolean``        ``// flag is false``        ``hasCycle = ``false``;`` ` `        ``// Store the resultant path``        ``ArrayList path``            ``= ``new` `ArrayList<>();``        ``path.add(``0``);`` ` `        ``// Keeps the track of the``        ``// visited vertices``        ``boolean``[] visited``            ``= ``new` `boolean``[graph.length];`` ` `        ``for` `(``int` `i = ``0``;``             ``i < visited.length; i++)``            ``visited[i] = ``false``;`` ` `        ``visited[``0``] = ``true``;`` ` `        ``// Function call to find all``        ``// hamiltonian cycles``        ``FindHamCycle(graph, ``1``, path,``                     ``visited);`` ` `        ``if` `(!hasCycle) {`` ` `            ``// If no Hamiltonian Cycle``            ``// is possible for the``            ``// given graph``            ``System.out.println(``                ``"No Hamiltonian Cycle"``                ``+ ``"possible "``);``            ``return``;``        ``}``    ``}`` ` `    ``// Recursive function to find all``    ``// hamiltonian cycles``    ``void` `FindHamCycle(``int` `graph[][], ``int` `pos,``                      ``ArrayList path,``                      ``boolean``[] visited)``    ``{``        ``// If all vertices are included``        ``// in Hamiltonian Cycle``        ``if` `(pos == graph.length) {`` ` `            ``// If there is an edge``            ``// from the last vertex to``            ``// the source vertex``            ``if` `(graph[path.get(path.size() - ``1``)]``                     ``[path.get(``0``)]``                ``!= ``0``) {`` ` `                ``// Include source vertex``                ``// into the path and``                ``// print the path``                ``path.add(``0``);``                ``for` `(``int` `i = ``0``;``                     ``i < path.size(); i++) {``                    ``System.out.print(``                        ``path.get(i) + ``" "``);``                ``}``                ``System.out.println();`` ` `                ``// Remove the source``                ``// vertex added``                ``path.remove(path.size() - ``1``);`` ` `                ``// Update the hasCycle``                ``// as true``                ``hasCycle = ``true``;``            ``}``            ``return``;``        ``}`` ` `        ``// Try different vertices``        ``// as the next vertex``        ``for` `(``int` `v = ``0``;``             ``v < graph.length; v++) {`` ` `            ``// Check if this vertex can``            ``// be added to Cycle``            ``if` `(isSafe(v, graph, path, pos)``                ``&& !visited[v]) {`` ` `                ``path.add(v);``                ``visited[v] = ``true``;`` ` `                ``// Recur to construct``                ``// rest of the path``                ``FindHamCycle(``                    ``graph, pos + ``1``,``                    ``path, visited);`` ` `                ``// Remove current vertex``                ``// from path and process``                ``// other vertices``                ``visited[v] = ``false``;``                ``path.remove(``                    ``path.size() - ``1``);``            ``}``        ``}``    ``}`` ` `    ``// Driver Code``    ``public` `static` `void` `main(String args[])``    ``{``        ``GFG hamiltonian = ``new` `GFG();`` ` `        ``/* Input Graph:``           ``(0) - - -- (2)``            ``|   \   /  |``            ``|    (1)   |``            ``|   /  |   |``            ``| /    |   |``           ``(5)----(4)--(3)*/`` ` `        ``int``[][] graph = {``            ``{ ``0``, ``1``, ``1``, ``0``, ``0``, ``1` `},``            ``{ ``1``, ``0``, ``1``, ``0``, ``1``, ``1` `},``            ``{ ``1``, ``1``, ``0``, ``1``, ``0``, ``0` `},``            ``{ ``0``, ``0``, ``1``, ``0``, ``1``, ``0` `},``            ``{ ``0``, ``1``, ``0``, ``1``, ``0``, ``1` `},``            ``{ ``1``, ``1``, ``0``, ``0``, ``1``, ``0` `},``        ``};``        ``hamiltonian.hamCycle(graph);``    ``}``}`
Output:
```0 1 2 3 4 5 0
0 1 5 4 3 2 0
0 2 3 4 1 5 0
0 2 3 4 5 1 0
0 5 1 4 3 2 0
0 5 4 3 2 1 0
```

Time Complexity: O(N!)
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

My Personal Notes arrow_drop_up