-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Implement Hamiltonian Cycle Finder #731
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
vil02
merged 5 commits into
TheAlgorithms:master
from
sozelfist:feat/backtracking/hamiltonian_cycle
Jun 21, 2024
Merged
Changes from 4 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
0d31506
feat: implement Hamiltonian Cycle
sozelfist 7dcef78
ref: refactor implementation
sozelfist 559b865
feat: refactor implementation
sozelfist f30a57c
ref: refactor implementation
sozelfist e6f721c
ref: refactor implementation
sozelfist File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,298 @@ | ||
//! This module provides functionality to find a Hamiltonian cycle in a directed or undirected graph. | ||
//! Source: [Uncyclopedia](https://en.wikipedia.org/wiki/Hamiltonian_path_problem) | ||
|
||
use std::collections::HashSet; | ||
|
||
/// Represents potential errors when finding hamiltonian cycle on an adjacency matrix. | ||
#[derive(Debug, PartialEq, Eq)] | ||
pub enum FindHamiltonianCycleError { | ||
/// Indicates that the adjacency matrix is empty. | ||
EmptyAdjMat, | ||
/// Indicates that the adjacency matrix is not square. | ||
ImproperAdjMat, | ||
/// Indicates that the starting vertex is out of bounds. | ||
StartOutOfBound, | ||
} | ||
|
||
/// Represents a graph using an adjacency matrix. | ||
struct Graph { | ||
/// The adjacency matrix representing the graph. | ||
adjacency_matrix: Vec<Vec<bool>>, | ||
} | ||
|
||
impl Graph { | ||
/// Creates a new graph with the provided adjacency matrix. | ||
/// | ||
/// # Arguments | ||
/// | ||
/// * `adjacency_matrix` - A square matrix where each element indicates | ||
/// the presence (`true`) or absence (`false`) of an edge | ||
/// between two vertices. | ||
/// | ||
/// # Returns | ||
/// | ||
/// A `Result` containing the graph if successful, or an `FindHamiltonianCycleError` if there is an issue with the matrix. | ||
fn new(adjacency_matrix: Vec<Vec<bool>>) -> Result<Self, FindHamiltonianCycleError> { | ||
// Check if the adjacency matrix is empty. | ||
if adjacency_matrix.is_empty() { | ||
return Err(FindHamiltonianCycleError::EmptyAdjMat); | ||
} | ||
|
||
// Validate that the adjacency matrix is square. | ||
if adjacency_matrix | ||
.iter() | ||
.any(|row| row.len() != adjacency_matrix.len()) | ||
{ | ||
return Err(FindHamiltonianCycleError::ImproperAdjMat); | ||
} | ||
|
||
Ok(Self { adjacency_matrix }) | ||
} | ||
|
||
/// Returns the number of vertices in the graph. | ||
fn num_vertices(&self) -> usize { | ||
self.adjacency_matrix.len() | ||
} | ||
|
||
/// Determines if it is safe to include vertex `v` in the Hamiltonian cycle path. | ||
/// | ||
/// # Arguments | ||
/// | ||
/// * `v` - The index of the vertex being considered. | ||
/// * `visited` - A reference to the set of visited vertices. | ||
/// * `path` - A reference to the current path being explored. | ||
/// * `pos` - The position of the current vertex being considered. | ||
/// | ||
/// # Returns | ||
/// | ||
/// `true` if it is safe to include `v` in the path, `false` otherwise. | ||
fn is_safe(&self, v: usize, visited: &HashSet<usize>, path: &[usize], pos: usize) -> bool { | ||
sozelfist marked this conversation as resolved.
Show resolved
Hide resolved
|
||
// Check if the current vertex and the last vertex in the path are adjacent. | ||
if !self.adjacency_matrix[path[pos - 1]][v] { | ||
return false; | ||
} | ||
|
||
// Check if the vertex has already been included in the path. | ||
!visited.contains(&v) | ||
} | ||
|
||
/// Recursively searches for a Hamiltonian cycle. | ||
/// | ||
/// This function is called by `find_hamiltonian_cycle`. | ||
/// | ||
/// # Arguments | ||
/// | ||
/// * `path` - A mutable vector representing the current path being explored. | ||
/// * `visited` - A mutable set representing the visited vertices. | ||
/// * `pos` - The position of the current vertex being considered. | ||
/// | ||
/// # Returns | ||
/// | ||
/// `true` if a Hamiltonian cycle is found, `false` otherwise. | ||
fn hamiltonian_cycle_util( | ||
&self, | ||
path: &mut Vec<usize>, | ||
visited: &mut HashSet<usize>, | ||
pos: usize, | ||
) -> bool { | ||
if pos == self.num_vertices() { | ||
// Check if there is an edge from the last included vertex to the first vertex. | ||
return self.adjacency_matrix[path[pos - 1]][path[0]]; | ||
} | ||
|
||
for v in 0..self.num_vertices() { | ||
if self.is_safe(v, visited, path, pos) { | ||
path[pos] = v; | ||
visited.insert(v); | ||
if self.hamiltonian_cycle_util(path, visited, pos + 1) { | ||
return true; | ||
} | ||
path[pos] = usize::MAX; | ||
visited.remove(&v); | ||
} | ||
} | ||
|
||
false | ||
} | ||
|
||
/// Attempts to find a Hamiltonian cycle in the graph, starting from the specified vertex. | ||
/// | ||
/// A Hamiltonian cycle visits every vertex exactly once and returns to the starting vertex. | ||
/// | ||
/// # Note | ||
/// This implementation may not find all possible Hamiltonian cycles. | ||
/// It stops as soon as it finds one valid cycle. If multiple Hamiltonian cycles exist, | ||
/// only one will be returned. | ||
/// | ||
/// # Returns | ||
/// | ||
/// `Ok(Some(path))` if a Hamiltonian cycle is found, where `path` is a vector | ||
/// containing the indices of vertices in the cycle, starting and ending with the same vertex. | ||
/// | ||
/// `Ok(None)` if no Hamiltonian cycle exists. | ||
fn find_hamiltonian_cycle( | ||
&self, | ||
start_vertex: usize, | ||
) -> Result<Option<Vec<usize>>, FindHamiltonianCycleError> { | ||
// Validate the start vertex. | ||
if start_vertex >= self.num_vertices() { | ||
return Err(FindHamiltonianCycleError::StartOutOfBound); | ||
} | ||
|
||
// Initialize the path. | ||
let mut path = vec![usize::MAX; self.adjacency_matrix.len()]; | ||
sozelfist marked this conversation as resolved.
Show resolved
Hide resolved
|
||
// Start at the specified vertex. | ||
path[0] = start_vertex; | ||
|
||
// Initialize the visited set. | ||
let mut visited = HashSet::new(); | ||
visited.insert(start_vertex); | ||
|
||
if self.hamiltonian_cycle_util(&mut path, &mut visited, 1) { | ||
// Complete the cycle by returning to the starting vertex. | ||
path.push(start_vertex); | ||
Ok(Some(path)) | ||
} else { | ||
Ok(None) | ||
} | ||
} | ||
} | ||
|
||
/// Attempts to find a Hamiltonian cycle in a graph represented by an adjacency matrix, starting from a specified vertex. | ||
pub fn find_hamiltonian_cycle( | ||
adjacency_matrix: Vec<Vec<bool>>, | ||
start_vertex: usize, | ||
sozelfist marked this conversation as resolved.
Show resolved
Hide resolved
|
||
) -> Result<Option<Vec<usize>>, FindHamiltonianCycleError> { | ||
Graph::new(adjacency_matrix)?.find_hamiltonian_cycle(start_vertex) | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use super::*; | ||
|
||
macro_rules! hamiltonian_cycle_tests { | ||
($($name:ident: $test_case:expr,)*) => { | ||
$( | ||
#[test] | ||
fn $name() { | ||
let (adjacency_matrix, start_vertex, expected) = $test_case; | ||
let result = find_hamiltonian_cycle(adjacency_matrix, start_vertex); | ||
assert_eq!(result, expected); | ||
vil02 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
)* | ||
}; | ||
} | ||
|
||
hamiltonian_cycle_tests! { | ||
test_complete_graph: ( | ||
vec![ | ||
vec![false, true, true, true], | ||
vec![true, false, true, true], | ||
vec![true, true, false, true], | ||
vec![true, true, true, false], | ||
], | ||
0, | ||
Ok(Some(vec![0, 1, 2, 3, 0])) | ||
), | ||
test_directed_graph_with_cycle: ( | ||
vec![ | ||
vec![false, true, false, false, false], | ||
vec![false, false, true, true, false], | ||
vec![true, false, false, true, true], | ||
vec![false, false, true, false, true], | ||
vec![true, true, false, false, false], | ||
], | ||
2, | ||
Ok(Some(vec![2, 3, 4, 0, 1, 2])) | ||
), | ||
test_undirected_graph_with_cycle: ( | ||
vec![ | ||
vec![false, true, false, false, true], | ||
vec![true, false, true, false, false], | ||
vec![false, true, false, true, false], | ||
vec![false, false, true, false, true], | ||
vec![true, false, false, true, false], | ||
], | ||
2, | ||
Ok(Some(vec![2, 1, 0, 4, 3, 2])) | ||
), | ||
test_directed_graph_no_cycle: ( | ||
vec![ | ||
vec![false, true, false, true, false], | ||
vec![false, false, true, true, false], | ||
vec![false, false, false, true, false], | ||
vec![false, false, false, false, true], | ||
vec![false, false, true, false, false], | ||
], | ||
0, | ||
Ok(None::<Vec<usize>>) | ||
), | ||
test_undirected_graph_no_cycle: ( | ||
vec![ | ||
vec![false, true, false, false, false], | ||
vec![true, false, true, true, false], | ||
vec![false, true, false, true, true], | ||
vec![false, true, true, false, true], | ||
vec![false, false, true, true, false], | ||
], | ||
0, | ||
Ok(None::<Vec<usize>>) | ||
), | ||
test_triangle_graph: ( | ||
vec![ | ||
vec![false, true, false], | ||
vec![false, false, true], | ||
vec![true, false, false], | ||
], | ||
1, | ||
Ok(Some(vec![1, 2, 0, 1])) | ||
), | ||
test_tree_graph: ( | ||
vec![ | ||
vec![false, true, false, true, false], | ||
vec![true, false, true, true, false], | ||
vec![false, true, false, false, false], | ||
vec![true, true, false, false, true], | ||
vec![false, false, false, true, false], | ||
], | ||
0, | ||
Ok(None::<Vec<usize>>) | ||
), | ||
test_empty_graph: ( | ||
vec![], | ||
0, | ||
Err(FindHamiltonianCycleError::EmptyAdjMat) | ||
), | ||
test_improper_graph: ( | ||
vec![ | ||
vec![false, true], | ||
vec![true], | ||
vec![false, true, true], | ||
vec![true, true, true, false] | ||
], | ||
0, | ||
Err(FindHamiltonianCycleError::ImproperAdjMat) | ||
), | ||
test_start_out_of_bound: ( | ||
vec![ | ||
vec![false, true, true], | ||
vec![true, false, true], | ||
vec![true, true, false], | ||
], | ||
3, | ||
Err(FindHamiltonianCycleError::StartOutOfBound) | ||
), | ||
test_complex_directed_graph: ( | ||
vec![ | ||
vec![false, true, false, true, false, false], | ||
vec![false, false, true, false, true, false], | ||
vec![false, false, false, true, false, false], | ||
vec![false, true, false, false, true, false], | ||
vec![false, false, true, false, false, true], | ||
vec![true, false, false, false, false, false], | ||
], | ||
0, | ||
Ok(Some(vec![0, 1, 2, 3, 4, 5, 0])) | ||
), | ||
sozelfist marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.