god_graph/generators/
grid.rs1use crate::graph::builders::GraphBuilder;
4use crate::graph::Graph;
5
6pub fn grid_graph<T>(rows: usize, cols: usize, diagonal: bool) -> Graph<T, f64>
16where
17 T: Clone + Default,
18{
19 let n = rows * cols;
20 let mut builder = GraphBuilder::undirected().with_nodes((0..n).map(|_| T::default()));
21
22 for r in 0..rows {
23 for c in 0..cols {
24 let idx = r * cols + c;
25
26 if c + 1 < cols {
28 builder = builder.with_edge(idx, idx + 1, 1.0);
29 }
30
31 if r + 1 < rows {
33 builder = builder.with_edge(idx, idx + cols, 1.0);
34 }
35
36 if diagonal {
38 if r + 1 < rows && c + 1 < cols {
39 builder = builder.with_edge(idx, idx + cols + 1, 1.0);
40 }
41 if r + 1 < rows && c > 0 {
42 builder = builder.with_edge(idx, idx + cols - 1, 1.0);
43 }
44 }
45 }
46 }
47
48 builder.build().unwrap_or_else(|_| Graph::undirected())
49}