Log In Sign Up
Day 51

Day 51: Hamiltonian Cycle

51/60 Days

Day 51: Hamiltonian Cycle #

Welcome to Day 51 of our 60 Days of Coding Algorithm Challenge! Today, we’ll explore the Hamiltonian Cycle problem, a classic problem in graph theory that demonstrates the power and limitations of backtracking algorithms.

What is a Hamiltonian Cycle? #

A Hamiltonian cycle (or Hamiltonian circuit) is a cycle in an undirected graph that visits each vertex exactly once and returns to the starting vertex. It’s named after the mathematician William Rowan Hamilton.

Understanding the Problem #

  • We have an undirected graph G = (V, E), where V is the set of vertices and E is the set of edges.
  • We need to find a cycle that visits every vertex exactly once and returns to the starting vertex.
  • If such a cycle exists, the graph is called Hamiltonian.

Backtracking Approach #

We’ll use a backtracking approach to solve this problem:

  1. Start from a vertex (typically vertex 0).
  2. Add the current vertex to the path.
  3. If all vertices are visited and there’s an edge from the last vertex to the first vertex, we’ve found a Hamiltonian cycle.
  4. Otherwise, try adding each adjacent unvisited vertex to the path.
  5. If adding a vertex …