-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
Copy pathhamiltonian_cycle.rs
310 lines (291 loc) · 10.5 KB
/
hamiltonian_cycle.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
//! This module provides functionality to find a Hamiltonian cycle in a directed or undirected graph.
//! Source: [Wikipedia](https://en.wikipedia.org/wiki/Hamiltonian_path_problem)
/// 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.
EmptyAdjacencyMatrix,
/// Indicates that the adjacency matrix is not square.
ImproperAdjacencyMatrix,
/// 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::EmptyAdjacencyMatrix);
}
// Validate that the adjacency matrix is square.
if adjacency_matrix
.iter()
.any(|row| row.len() != adjacency_matrix.len())
{
return Err(FindHamiltonianCycleError::ImproperAdjacencyMatrix);
}
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 vector representing the 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: &[bool], path: &[Option<usize>], pos: usize) -> bool {
// Check if the current vertex and the last vertex in the path are adjacent.
if !self.adjacency_matrix[path[pos - 1].unwrap()][v] {
return false;
}
// Check if the vertex has already been included in the path.
!visited[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 vector 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 [Option<usize>],
visited: &mut [bool],
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].unwrap()][path[0].unwrap()];
}
for v in 0..self.num_vertices() {
if self.is_safe(v, visited, path, pos) {
path[pos] = Some(v);
visited[v] = true;
if self.hamiltonian_cycle_util(path, visited, pos + 1) {
return true;
}
path[pos] = None;
visited[v] = false;
}
}
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![None; self.num_vertices()];
// Start at the specified vertex.
path[0] = Some(start_vertex);
// Initialize the visited vector.
let mut visited = vec![false; self.num_vertices()];
visited[start_vertex] = true;
if self.hamiltonian_cycle_util(&mut path, &mut visited, 1) {
// Complete the cycle by returning to the starting vertex.
path.push(Some(start_vertex));
Ok(Some(path.into_iter().map(Option::unwrap).collect()))
} 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,
) -> 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);
}
)*
};
}
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::EmptyAdjacencyMatrix)
),
test_improper_graph: (
vec![
vec![false, true],
vec![true],
vec![false, true, true],
vec![true, true, true, false]
],
0,
Err(FindHamiltonianCycleError::ImproperAdjacencyMatrix)
),
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]))
),
single_node_self_loop: (
vec![
vec![true],
],
0,
Ok(Some(vec![0, 0]))
),
single_node: (
vec![
vec![false],
],
0,
Ok(None)
),
}
}