use std::collections::{HashSet, VecDeque};
use rustworkx_core::connectivity::number_connected_components as rx_ncc;
use crate::Hypergraph;
fn bfs_component<N, E, M>(h: &Hypergraph<N, E, M>, source: &str) -> HashSet<String> {
let mut seen: HashSet<String> = HashSet::new();
let mut queue: VecDeque<String> = VecDeque::new();
seen.insert(source.to_string());
queue.push_back(source.to_string());
while let Some(cur) = queue.pop_front() {
for nb in h.node_neighbors(&cur).unwrap_or_default() {
if seen.insert(nb.clone()) {
queue.push_back(nb);
}
}
}
seen
}
pub fn connected_components<N, E, M>(h: &Hypergraph<N, E, M>) -> Vec<Vec<String>> {
let node_ids = h.node_ids();
let mut seen: HashSet<String> = HashSet::new();
let mut components: Vec<Vec<String>> = Vec::new();
for v in &node_ids {
if !seen.contains(v) {
let comp = bfs_component(h, v);
seen.extend(comp.iter().cloned());
let ordered: Vec<String> = node_ids
.iter()
.filter(|n| comp.contains(*n))
.cloned()
.collect();
components.push(ordered);
}
}
components
}
pub fn is_connected<N, E, M>(h: &Hypergraph<N, E, M>) -> bool {
if h.num_nodes() == 0 {
return false;
}
number_connected_components(h) == 1
}
pub fn number_connected_components<N, E, M>(h: &Hypergraph<N, E, M>) -> usize {
let g = h.skeleton();
rx_ncc(&g)
}
pub fn node_connected_component<N, E, M>(h: &Hypergraph<N, E, M>, n: &str) -> Option<Vec<String>> {
if !h.has_node(n) {
return None;
}
let comp = bfs_component(h, n);
Some(
h.node_ids()
.into_iter()
.filter(|x| comp.contains(x))
.collect(),
)
}
pub fn largest_connected_component<N, E, M>(h: &Hypergraph<N, E, M>) -> Vec<String> {
connected_components(h)
.into_iter()
.max_by_key(|c| c.len())
.unwrap_or_default()
}