use crate::common::empty_graph_with_capacity;
use petgraph::graph::{IndexType, NodeIndex};
use petgraph::{EdgeType, Graph};
pub fn complete_graph<Ty: EdgeType, Ix: IndexType>(n: usize) -> Graph<(), (), Ty, Ix> {
let mut graph = empty_graph_with_capacity(n, n, n * n);
if n <= 1 {
return graph;
}
for i in 0..n - 1 {
for j in i + 1..n {
graph.add_edge(NodeIndex::new(i), NodeIndex::new(j), ());
if Ty::is_directed() {
graph.add_edge(NodeIndex::new(j), NodeIndex::new(i), ());
}
}
}
graph
}
pub fn empty_graph<Ty: EdgeType, Ix: IndexType>(n: usize) -> Graph<(), (), Ty, Ix> {
empty_graph_with_capacity(n, n, 0)
}
pub fn star_graph<Ty: EdgeType, Ix: IndexType>(n: usize) -> Graph<(), (), Ty, Ix> {
let mut graph = Graph::with_capacity(n + 1, n);
let center = graph.add_node(());
for _ in 0..n {
let node = graph.add_node(());
graph.add_edge(center, node, ());
}
graph
}
#[cfg(test)]
mod tests {
use super::*;
use crate::common::assert_graph_eq;
use petgraph::graph::{DiGraph, UnGraph};
#[test]
fn test_complete_directed_graph() {
let graph: DiGraph<(), (), u32> = complete_graph(4);
let expected = Graph::from_edges(&[
(0, 1),
(1, 0),
(0, 2),
(2, 0),
(0, 3),
(3, 0),
(1, 2),
(2, 1),
(1, 3),
(3, 1),
(2, 3),
(3, 2),
]);
assert_graph_eq(&graph, &expected);
}
#[test]
fn test_complete_undirected_graph() {
let graph: UnGraph<(), (), u16> = complete_graph(4);
let expected = Graph::from_edges(&[(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]);
assert_graph_eq(&graph, &expected);
}
}