R
R copied to clipboard
Add Hamiltonian Path in R
Overview
The hamiltonianPath function attempts to construct a valid Hamiltonian Path by recursively adding vertices to a path while ensuring adjacency and non-repetition constraints.
If the input adjacency matrix does not contain a Hamiltonian Path, the algorithm reports that no valid path was found.
This implementation provides a clear, educational example of graph backtracking and can be extended to find Hamiltonian Cycles as well.
Features
- Implements a backtracking-based Hamiltonian Path search
- Accepts input as an adjacency matrix (n × n)
- Verifies adjacency and uniqueness at each recursive step
- Prints the Hamiltonian Path when found
- Returns logical
TRUEif a path exists, otherwiseFALSE - Includes a sample graph and example usage block for demonstration
Complexity
- Time Complexity: O(n!) in the worst case (backtracking over all vertex permutations)
- Space Complexity: O(n) for recursion stack and path storage