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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
//! Weakly chordal graph predicate (ALGO-PR-121).
//!
//! A graph is weakly chordal (also called weakly triangulated) if
//! neither G nor its complement contains an induced cycle of length
//! ≥ 5. Equivalently, every induced cycle in both G and its
//! complement has length at most 4.
//!
//! Every chordal graph is weakly chordal (no induced `C_k` for k ≥ 4).
//! Every co-chordal graph (complement is chordal) is weakly chordal.
//!
//! Directed graphs are treated as undirected.
use crate::core::{Graph, IgraphResult};
/// Check whether a graph is weakly chordal.
///
/// A graph is weakly chordal if neither G nor its complement has an
/// induced cycle of length ≥ 5. Uses chordality checks on both G
/// and its complement; if both are chordal, G is weakly chordal.
/// Otherwise, checks for induced ``C_k`` (k ≥ 5) in the non-chordal
/// graph(s).
///
/// Directed graphs are treated as undirected.
///
/// # Examples
///
/// ```
/// use rust_igraph::{Graph, is_weakly_chordal};
///
/// // `K_4`: chordal → weakly chordal
/// let mut g = Graph::with_vertices(4);
/// for i in 0..4u32 {
/// for j in (i+1)..4 {
/// g.add_edge(i, j).unwrap();
/// }
/// }
/// assert!(is_weakly_chordal(&g).unwrap());
///
/// // `C_5` is NOT weakly chordal (is its own induced C_5)
/// let mut g = Graph::with_vertices(5);
/// g.add_edge(0, 1).unwrap();
/// g.add_edge(1, 2).unwrap();
/// g.add_edge(2, 3).unwrap();
/// g.add_edge(3, 4).unwrap();
/// g.add_edge(4, 0).unwrap();
/// assert!(!is_weakly_chordal(&g).unwrap());
/// ```
pub fn is_weakly_chordal(graph: &Graph) -> IgraphResult<bool> {
let n = graph.vcount();
if n <= 4 {
return Ok(true);
}
let n_usize = n as usize;
let mut adj = vec![vec![false; n_usize]; n_usize];
for v in 0..n {
let nbrs = graph.neighbors(v)?;
for &w in &nbrs {
adj[v as usize][w as usize] = true;
adj[w as usize][v as usize] = true;
}
}
// Check if G has an induced `C_k` for k ≥ 5
if has_long_induced_cycle(&adj, n_usize) {
return Ok(false);
}
// Build complement adjacency
let mut comp = vec![vec![false; n_usize]; n_usize];
for i in 0..n_usize {
for j in (i + 1)..n_usize {
if !adj[i][j] {
comp[i][j] = true;
comp[j][i] = true;
}
}
}
// Check if complement has an induced `C_k` for k ≥ 5
if has_long_induced_cycle(&comp, n_usize) {
return Ok(false);
}
Ok(true)
}
/// Check if a graph (given by adjacency matrix) has an induced cycle
/// of length ≥ 5. Uses DFS to find chordless cycles.
fn has_long_induced_cycle(adj: &[Vec<bool>], n: usize) -> bool {
// A graph has no induced `C_k` (k ≥ 5) iff it is "hole-free for k≥5".
// We can check this by looking for chordless cycles of length ≥ 5.
// Approach: for each edge (u,v), try to find a chordless path from
// v back to u of length ≥ 4 (so total cycle ≥ 5) that avoids
// non-path neighbors of u.
// Simpler approach: check if chordal. If chordal, no induced `C_k`
// for k ≥ 4, so certainly no k ≥ 5.
// If not chordal, there exists an induced `C_k` for k ≥ 4.
// If k = 4, that's fine (weakly chordal allows C_4).
// If k ≥ 5, that's a violation.
// So we need to check: is there an induced `C_k` for k ≥ 5?
// If the graph is chordal, return false.
// If the graph has an induced C_4 but no induced `C_k` (k ≥ 5),
// return false.
// For the DFS approach: enumerate chordless cycles.
// For each vertex u, for each pair of non-adjacent neighbors (v,w),
// try to find a chordless path from v to w not through u and not
// using any other neighbor of u (to ensure chordless cycle with u).
// If path length ≥ 3, cycle length = path + 2 ≥ 5.
for u in 0..n {
let nbrs_u: Vec<usize> = (0..n).filter(|&v| adj[u][v]).collect();
for (i, &v) in nbrs_u.iter().enumerate() {
for &w in &nbrs_u[(i + 1)..] {
if adj[v][w] {
continue;
}
// v and w are non-adjacent neighbors of u.
// Find chordless path from v to w not through u,
// where internal vertices are not neighbors of u
// (to ensure the cycle u-v-...-w-u is chordless).
if chordless_path_exists(adj, v, w, u, &nbrs_u, n, 3) {
return true;
}
}
}
}
false
}
/// Check if there exists a chordless path from `start` to `end` of
/// length ≥ `min_len`, not passing through `excluded`, where
/// internal vertices are not in `forbidden` (neighbors of the cycle
/// anchor) and are not adjacent to both `start`'s predecessor and
/// `end` (to maintain chordlessness).
fn chordless_path_exists(
adj: &[Vec<bool>],
start: usize,
end: usize,
excluded: usize,
forbidden_set: &[usize],
n: usize,
min_len: usize,
) -> bool {
// BFS/DFS to find path from start to end of length ≥ min_len
// through vertices that are not in forbidden_set and not excluded.
let mut forbidden = vec![false; n];
forbidden[excluded] = true;
for &f in forbidden_set {
if f != start && f != end {
forbidden[f] = true;
}
}
// DFS with path tracking
let mut path = vec![start];
let mut visited = vec![false; n];
visited[start] = true;
visited[excluded] = true;
dfs_chordless(adj, &mut path, &mut visited, end, &forbidden, n, min_len)
}
fn dfs_chordless(
adj: &[Vec<bool>],
path: &mut Vec<usize>,
visited: &mut Vec<bool>,
target: usize,
forbidden: &[bool],
n: usize,
min_len: usize,
) -> bool {
let Some(¤t) = path.last() else {
return false;
};
let depth = path.len();
// If current depth ≥ min_len and we can reach target
if depth >= min_len && adj[current][target] {
// Check chordlessness: no internal vertex adjacent to target
// except the last one (current).
// Actually we need: no chord in the cycle. The cycle is
// excluded - start - path - target - excluded.
// We already ensured internal vertices are not neighbors of
// excluded. We need to check that no internal vertex of the
// path (indices 1..depth-1) is adjacent to target.
let chordless = path[1..depth - 1].iter().all(|&v| !adj[v][target]);
if chordless {
return true;
}
}
// Limit search depth to avoid exponential blowup
if depth >= n.min(12) {
return false;
}
for next in 0..n {
if visited[next] || forbidden[next] || next == target && depth < min_len - 1 {
continue;
}
if !adj[current][next] {
continue;
}
// Check chordlessness: next must not be adjacent to any
// path vertex except current (the immediately previous one)
let has_chord = path[..depth - 1].iter().any(|&v| adj[next][v]);
if has_chord {
continue;
}
visited[next] = true;
path.push(next);
if dfs_chordless(adj, path, visited, target, forbidden, n, min_len) {
return true;
}
path.pop();
visited[next] = false;
}
false
}
#[cfg(test)]
mod tests {
use super::*;
use crate::algorithms::chordality::is_chordal;
#[test]
fn empty_graph() {
let g = Graph::with_vertices(0);
assert!(is_weakly_chordal(&g).unwrap());
}
#[test]
fn single_vertex() {
let g = Graph::with_vertices(1);
assert!(is_weakly_chordal(&g).unwrap());
}
#[test]
fn single_edge() {
let mut g = Graph::with_vertices(2);
g.add_edge(0, 1).unwrap();
assert!(is_weakly_chordal(&g).unwrap());
}
#[test]
fn triangle() {
let mut g = Graph::with_vertices(3);
g.add_edge(0, 1).unwrap();
g.add_edge(1, 2).unwrap();
g.add_edge(2, 0).unwrap();
assert!(is_weakly_chordal(&g).unwrap());
}
#[test]
fn c4_weakly_chordal() {
// C_4 is weakly chordal (induced C_4 is allowed, only C_5+ banned)
let mut g = Graph::with_vertices(4);
g.add_edge(0, 1).unwrap();
g.add_edge(1, 2).unwrap();
g.add_edge(2, 3).unwrap();
g.add_edge(3, 0).unwrap();
assert!(is_weakly_chordal(&g).unwrap());
}
#[test]
fn c5_not_weakly_chordal() {
let mut g = Graph::with_vertices(5);
g.add_edge(0, 1).unwrap();
g.add_edge(1, 2).unwrap();
g.add_edge(2, 3).unwrap();
g.add_edge(3, 4).unwrap();
g.add_edge(4, 0).unwrap();
assert!(!is_weakly_chordal(&g).unwrap());
}
#[test]
fn c6_not_weakly_chordal() {
let mut g = Graph::with_vertices(6);
for i in 0..6u32 {
g.add_edge(i, (i + 1) % 6).unwrap();
}
assert!(!is_weakly_chordal(&g).unwrap());
}
#[test]
fn complete_k5() {
// Chordal → weakly chordal
let mut g = Graph::with_vertices(5);
for i in 0..5u32 {
for j in (i + 1)..5 {
g.add_edge(i, j).unwrap();
}
}
assert!(is_weakly_chordal(&g).unwrap());
}
#[test]
fn chordal_graph() {
// Any chordal graph is weakly chordal
let mut g = Graph::with_vertices(5);
g.add_edge(0, 1).unwrap();
g.add_edge(0, 2).unwrap();
g.add_edge(1, 2).unwrap();
g.add_edge(2, 3).unwrap();
g.add_edge(2, 4).unwrap();
g.add_edge(3, 4).unwrap();
assert!(is_chordal(&g, None).unwrap().chordal);
assert!(is_weakly_chordal(&g).unwrap());
}
#[test]
fn edgeless() {
// Complement of 5 isolated vertices is K_5 (chordal) → weakly chordal
let g = Graph::with_vertices(5);
assert!(is_weakly_chordal(&g).unwrap());
}
#[test]
fn path_p5() {
// P_5 is a tree → no induced cycle in G.
// Complement edges: 0-2,0-3,0-4,1-3,1-4,2-4.
// Cycle 0-2-4-1-3-0 has chord 0-4, so no induced C_5.
// → P_5 is weakly chordal.
let mut g = Graph::with_vertices(5);
g.add_edge(0, 1).unwrap();
g.add_edge(1, 2).unwrap();
g.add_edge(2, 3).unwrap();
g.add_edge(3, 4).unwrap();
assert!(is_weakly_chordal(&g).unwrap());
}
#[test]
fn star() {
// Star S_4: center 0, leaves 1,2,3,4.
// G is a tree → chordal → no induced C_5+ in G.
// Complement: 0 isolated, 1-2-3-4 complete (K_4).
// K_4 is chordal → no induced C_5+ in complement.
// → weakly chordal
let mut g = Graph::with_vertices(5);
g.add_edge(0, 1).unwrap();
g.add_edge(0, 2).unwrap();
g.add_edge(0, 3).unwrap();
g.add_edge(0, 4).unwrap();
assert!(is_weakly_chordal(&g).unwrap());
}
#[test]
fn diamond() {
let mut g = Graph::with_vertices(4);
g.add_edge(0, 1).unwrap();
g.add_edge(0, 2).unwrap();
g.add_edge(0, 3).unwrap();
g.add_edge(1, 2).unwrap();
g.add_edge(1, 3).unwrap();
assert!(is_weakly_chordal(&g).unwrap());
}
#[test]
fn directed_treated_as_undirected() {
let mut g = Graph::new(4, true).unwrap();
g.add_edge(0, 1).unwrap();
g.add_edge(1, 2).unwrap();
g.add_edge(2, 3).unwrap();
g.add_edge(3, 0).unwrap();
assert!(is_weakly_chordal(&g).unwrap());
}
}