pathfinding-indexed 4.15.0

Index-only pathfinding, flow, and graph algorithms
Documentation
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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
//! Indexed graph storage and algorithms.

use num_traits::{Bounded, Signed, Zero};
use rustc_hash::{FxHashMap, FxHashSet};
use std::collections::VecDeque;
use std::hash::Hash;
use thiserror::Error;

/// Errors returned by indexed input helper constructors.
#[derive(Clone, Debug, Eq, Error, PartialEq)]
pub enum IndexedInputError {
    /// Matrix rows do not all have the same length.
    #[error("matrix rows must all have the same length")]
    RaggedMatrix,
    /// Adjacency matrices must be square.
    #[error("adjacency matrix must be square")]
    NonSquareAdjacencyMatrix,
}

/// A directed graph stored as dense `usize` indices with weighted adjacency lists.
#[derive(Clone, Debug)]
pub struct IndexedGraph<C> {
    adjacency: Vec<Vec<(usize, C)>>,
}

impl<C> IndexedGraph<C> {
    /// Build a directed indexed graph from an adjacency list.
    #[must_use]
    pub const fn from_adjacency(adjacency: Vec<Vec<(usize, C)>>) -> Self {
        Self { adjacency }
    }

    /// Return the number of nodes in the graph.
    #[must_use]
    pub const fn node_count(&self) -> usize {
        self.adjacency.len()
    }

    /// Return the number of nodes in the graph.
    #[must_use]
    pub const fn len(&self) -> usize {
        self.adjacency.len()
    }

    /// Return true if the graph contains no nodes.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.adjacency.is_empty()
    }

    /// Return the adjacency list for `node`.
    #[must_use]
    pub fn successors(&self, node: usize) -> &[(usize, C)] {
        &self.adjacency[node]
    }

    /// Return all adjacency lists.
    #[must_use]
    pub fn adjacency(&self) -> &[Vec<(usize, C)>] {
        &self.adjacency
    }

    /// Run A* from `start` to a node satisfying `success`.
    pub fn astar<FH, FS>(
        &self,
        start: usize,
        mut heuristic: FH,
        mut success: FS,
    ) -> Option<(Vec<usize>, C)>
    where
        C: Zero + Ord + Copy,
        FH: FnMut(usize) -> C,
        FS: FnMut(usize) -> bool,
    {
        crate::directed::astar::astar(
            &start,
            |node| self.successors(*node).iter().copied(),
            |node| heuristic(*node),
            |node| success(*node),
        )
    }

    /// Run A* and return all shortest paths as an iterator.
    pub fn astar_bag<FH, FS>(
        &self,
        start: usize,
        mut heuristic: FH,
        mut success: FS,
    ) -> Option<(impl Iterator<Item = Vec<usize>>, C)>
    where
        C: Zero + Ord + Copy,
        FH: FnMut(usize) -> C,
        FS: FnMut(usize) -> bool,
    {
        crate::directed::astar::astar_bag(
            &start,
            |node| self.successors(*node).iter().copied(),
            |node| heuristic(*node),
            |node| success(*node),
        )
    }

    /// Run A* and collect all shortest paths into a vector.
    pub fn astar_bag_collect<FH, FS>(
        &self,
        start: usize,
        mut heuristic: FH,
        mut success: FS,
    ) -> Option<(Vec<Vec<usize>>, C)>
    where
        C: Zero + Ord + Copy,
        FH: FnMut(usize) -> C,
        FS: FnMut(usize) -> bool,
    {
        crate::directed::astar::astar_bag_collect(
            &start,
            |node| self.successors(*node).iter().copied(),
            |node| heuristic(*node),
            |node| success(*node),
        )
    }

    /// Run BFS from `start` to a node satisfying `success`.
    pub fn bfs<FS>(&self, start: usize, mut success: FS) -> Option<Vec<usize>>
    where
        FS: FnMut(usize) -> bool,
    {
        crate::directed::bfs::bfs(
            &start,
            |node| self.successors(*node).iter().map(|edge| edge.0),
            |node| success(*node),
        )
    }

    /// Run BFS and return the shortest loop starting and ending at `start`.
    #[must_use]
    pub fn bfs_loop(&self, start: usize) -> Option<Vec<usize>> {
        crate::directed::bfs::bfs_loop(&start, |node| {
            self.successors(*node).iter().map(|edge| edge.0)
        })
    }

    /// Run bidirectional BFS from `start` to `end`.
    #[must_use]
    pub fn bfs_bidirectional(&self, start: usize, end: usize) -> Option<Vec<usize>> {
        let mut predecessors = vec![Vec::new(); self.node_count()];
        for (from, edges) in self.adjacency.iter().enumerate() {
            for &(to, _) in edges {
                predecessors[to].push(from);
            }
        }

        crate::directed::bfs::bfs_bidirectional(
            &start,
            &end,
            |node| {
                self.successors(*node)
                    .iter()
                    .map(|edge| edge.0)
                    .collect::<Vec<_>>()
            },
            |node| predecessors[*node].clone(),
        )
    }

    /// Iterate over nodes reachable from `start` using BFS order.
    pub fn bfs_reach(&self, start: usize) -> impl Iterator<Item = usize> + '_ {
        crate::directed::bfs::bfs_reach(start, |node| {
            self.successors(*node).iter().map(|edge| edge.0)
        })
    }

    /// Run DFS from `start` to a node satisfying `success`.
    pub fn dfs<FS>(&self, start: usize, mut success: FS) -> Option<Vec<usize>>
    where
        FS: FnMut(usize) -> bool,
    {
        crate::directed::dfs::dfs(
            start,
            |node| self.successors(*node).iter().map(|edge| edge.0),
            |node| success(*node),
        )
    }

    /// Iterate over nodes reachable from `start` using DFS order.
    pub fn dfs_reach(&self, start: usize) -> impl Iterator<Item = usize> + '_ {
        crate::directed::dfs::dfs_reach(start, |node| {
            self.successors(*node).iter().map(|edge| edge.0)
        })
    }

    /// Run IDDFS from `start` to a node satisfying `success`.
    pub fn iddfs<FS>(&self, start: usize, mut success: FS) -> Option<Vec<usize>>
    where
        FS: FnMut(usize) -> bool,
    {
        crate::directed::iddfs::iddfs(
            start,
            |node| self.successors(*node).iter().map(|edge| edge.0),
            |node| success(*node),
        )
    }

    /// Run IDA* from `start` to a node satisfying `success`.
    pub fn idastar<FH, FS>(
        &self,
        start: usize,
        mut heuristic: FH,
        mut success: FS,
    ) -> Option<(Vec<usize>, C)>
    where
        C: Zero + Ord + Copy,
        FH: FnMut(usize) -> C,
        FS: FnMut(usize) -> bool,
    {
        crate::directed::idastar::idastar(
            &start,
            |node| self.successors(*node).iter().copied(),
            |node| heuristic(*node),
            |node| success(*node),
        )
    }

    /// Run Dijkstra from `start` to a node satisfying `success`.
    pub fn dijkstra<FS>(&self, start: usize, mut success: FS) -> Option<(Vec<usize>, C)>
    where
        C: Zero + Ord + Copy,
        FS: FnMut(usize) -> bool,
    {
        crate::directed::dijkstra::dijkstra(
            &start,
            |node| self.successors(*node).iter().copied(),
            |node| success(*node),
        )
    }

    /// Compute shortest paths to all reachable nodes from `start`.
    pub fn dijkstra_all(&self, start: usize) -> Vec<Option<(usize, C)>>
    where
        C: Zero + Ord + Copy,
    {
        let parents = crate::directed::dijkstra::dijkstra_all(&start, |node| {
            self.successors(*node).iter().copied()
        });
        let mut out = vec![None; self.node_count()];
        for (node, (parent, cost)) in parents {
            out[node] = Some((parent, cost));
        }
        out
    }

    /// Compute shortest paths until `stop` returns true.
    pub fn dijkstra_partial<FS>(
        &self,
        start: usize,
        mut stop: FS,
    ) -> (Vec<Option<(usize, C)>>, Option<usize>)
    where
        C: Zero + Ord + Copy,
        FS: FnMut(usize) -> bool,
    {
        let (parents, reached) = crate::directed::dijkstra::dijkstra_partial(
            &start,
            |node| self.successors(*node).iter().copied(),
            |node| stop(*node),
        );
        let mut out = vec![None; self.node_count()];
        for (node, (parent, cost)) in parents {
            out[node] = Some((parent, cost));
        }
        (out, reached)
    }

    /// Iterate over nodes reached by Dijkstra, yielding the node, parent, and total cost.
    pub fn dijkstra_reach(
        &self,
        start: usize,
    ) -> impl Iterator<Item = (usize, Option<usize>, C)> + '_
    where
        C: Zero + Ord + Copy + Hash,
    {
        crate::directed::dijkstra::dijkstra_reach(&start, |node| {
            self.successors(*node).iter().copied()
        })
        .map(|item| (item.node, item.parent, item.total_cost))
    }

    /// Run the BMSSP-based SSSP algorithm from `start`.
    pub fn bmssp<FS>(&self, start: usize, success: FS) -> Option<(Vec<usize>, C)>
    where
        C: Zero + Ord + Copy,
        FS: FnMut(usize) -> bool,
    {
        crate::directed::bmssp::bmssp_indexed(
            start,
            |node| self.successors(node).iter().copied(),
            success,
            self.node_count(),
        )
    }

    /// Compute BMSSP parents and costs for all reachable nodes from `start`.
    #[must_use]
    pub fn bmssp_all(&self, start: usize) -> Vec<Option<(usize, C)>>
    where
        C: Zero + Ord + Copy,
    {
        crate::directed::bmssp::bmssp_all_indexed(
            start,
            |node| self.successors(node).iter().copied(),
            self.node_count(),
        )
    }

    /// Run Fringe search from `start` to a node satisfying `success`.
    pub fn fringe<FH, FS>(
        &self,
        start: usize,
        mut heuristic: FH,
        mut success: FS,
    ) -> Option<(Vec<usize>, C)>
    where
        C: Bounded + Zero + Ord + Copy,
        FH: FnMut(usize) -> C,
        FS: FnMut(usize) -> bool,
    {
        crate::directed::fringe::fringe(
            &start,
            |node| self.successors(*node).iter().copied(),
            |node| heuristic(*node),
            |node| success(*node),
        )
    }

    /// Compute a topological ordering of all nodes.
    ///
    /// # Errors
    ///
    /// Returns `Err(node)` when a cycle is detected.
    pub fn topological_sort(&self) -> Result<Vec<usize>, usize> {
        let nodes = (0..self.node_count()).collect::<Vec<_>>();
        crate::directed::topological_sort::topological_sort(&nodes, |node| {
            self.successors(*node).iter().map(|edge| edge.0)
        })
    }

    /// Compute strongly connected components for all nodes.
    #[must_use]
    pub fn strongly_connected_components(&self) -> Vec<Vec<usize>> {
        let nodes = (0..self.node_count()).collect::<Vec<_>>();
        crate::directed::strongly_connected_components::strongly_connected_components(
            &nodes,
            |node| self.successors(*node).iter().map(|edge| edge.0),
        )
    }

    /// Compute strongly connected components reachable from `start`.
    #[must_use]
    pub fn strongly_connected_components_from(&self, start: usize) -> Vec<Vec<usize>> {
        crate::directed::strongly_connected_components::strongly_connected_components_from(
            &start,
            |node| self.successors(*node).iter().map(|edge| edge.0),
        )
    }

    /// Compute the strongly connected component containing `node`.
    #[must_use]
    pub fn strongly_connected_component(&self, node: usize) -> Vec<usize> {
        crate::directed::strongly_connected_components::strongly_connected_component(&node, |n| {
            self.successors(*n).iter().map(|edge| edge.0)
        })
    }

    /// Count the number of paths from `start` to nodes satisfying `success`.
    pub fn count_paths<FS>(&self, start: usize, mut success: FS) -> usize
    where
        FS: FnMut(usize) -> bool,
    {
        crate::directed::count_paths::count_paths(
            start,
            |node| self.successors(*node).iter().map(|edge| edge.0),
            |node| success(*node),
        )
    }

    /// Compute k-shortest paths using Yen's algorithm.
    pub fn yen<FS>(&self, start: usize, mut success: FS, k: usize) -> Vec<(Vec<usize>, C)>
    where
        C: Zero + Ord + Copy,
        FS: FnMut(usize) -> bool,
    {
        crate::directed::yen::yen(
            &start,
            |node| self.successors(*node).iter().copied(),
            |node| success(*node),
            k,
        )
    }

    /// Compute the maximum flow and minimum cut using Edmonds-Karp.
    ///
    /// # Panics
    ///
    /// Panics if `source` or `sink` are out of bounds.
    #[expect(clippy::too_many_lines)]
    #[expect(clippy::type_complexity)]
    #[must_use]
    pub fn edmonds_karp(
        &self,
        source: usize,
        sink: usize,
    ) -> (Vec<((usize, usize), C)>, C, Vec<((usize, usize), C)>)
    where
        C: Copy + Zero + Signed + Ord + Bounded,
    {
        let node_count = self.node_count();
        if node_count == 0 || source == sink {
            return (Vec::new(), Zero::zero(), Vec::new());
        }
        assert!(source < node_count, "source out of bounds");
        assert!(sink < node_count, "sink out of bounds");

        let mut capacity = vec![vec![C::zero(); node_count]; node_count];
        for (from, edges) in self.adjacency.iter().enumerate() {
            for &(to, weight) in edges {
                capacity[from][to] = capacity[from][to] + weight;
            }
        }

        let mut predecessors = vec![Vec::new(); node_count];
        for (from, edges) in self.adjacency.iter().enumerate() {
            for &(to, _) in edges {
                predecessors[to].push(from);
            }
        }

        let mut flow = vec![vec![C::zero(); node_count]; node_count];
        let mut total = C::zero();

        loop {
            let mut parent = vec![usize::MAX; node_count];
            let mut direction = vec![true; node_count];
            let mut path_capacity = vec![C::zero(); node_count];
            let mut queue = VecDeque::new();

            parent[source] = source;
            path_capacity[source] = C::max_value();
            queue.push_back(source);

            while let Some(node) = queue.pop_front() {
                let capacity_so_far = path_capacity[node];
                for &(next, _) in &self.adjacency[node] {
                    if parent[next] != usize::MAX || next == source {
                        continue;
                    }
                    let residual = capacity[node][next] - flow[node][next];
                    if residual <= Zero::zero() {
                        continue;
                    }
                    parent[next] = node;
                    direction[next] = true;
                    path_capacity[next] = if capacity_so_far < residual {
                        capacity_so_far
                    } else {
                        residual
                    };
                    if next == sink {
                        break;
                    }
                    queue.push_back(next);
                }
                if parent[sink] != usize::MAX {
                    break;
                }
                for &prev in &predecessors[node] {
                    if parent[prev] != usize::MAX || prev == source {
                        continue;
                    }
                    let residual = flow[prev][node];
                    if residual <= Zero::zero() {
                        continue;
                    }
                    parent[prev] = node;
                    direction[prev] = false;
                    path_capacity[prev] = if capacity_so_far < residual {
                        capacity_so_far
                    } else {
                        residual
                    };
                    if prev == sink {
                        break;
                    }
                    queue.push_back(prev);
                }
                if parent[sink] != usize::MAX {
                    break;
                }
            }

            if parent[sink] == usize::MAX {
                break;
            }

            let augment = path_capacity[sink];
            let mut node = sink;
            while node != source {
                let prev = parent[node];
                if direction[node] {
                    flow[prev][node] = flow[prev][node] + augment;
                } else {
                    flow[node][prev] = flow[node][prev] - augment;
                }
                node = prev;
            }
            total = total + augment;
        }

        let mut reachable = vec![false; node_count];
        let mut queue = VecDeque::new();
        reachable[source] = true;
        queue.push_back(source);
        while let Some(node) = queue.pop_front() {
            for &(next, _) in &self.adjacency[node] {
                if reachable[next] {
                    continue;
                }
                let residual = capacity[node][next] - flow[node][next];
                if residual > Zero::zero() {
                    reachable[next] = true;
                    queue.push_back(next);
                }
            }
            for &prev in &predecessors[node] {
                if reachable[prev] {
                    continue;
                }
                if flow[prev][node] > Zero::zero() {
                    reachable[prev] = true;
                    queue.push_back(prev);
                }
            }
        }

        let mut flows = Vec::new();
        for (from, edges) in self.adjacency.iter().enumerate() {
            for &(to, _) in edges {
                let value = flow[from][to];
                if value > Zero::zero() {
                    flows.push(((from, to), value));
                }
            }
        }

        let mut cuts = Vec::new();
        for (from, edges) in self.adjacency.iter().enumerate() {
            if !reachable[from] {
                continue;
            }
            for &(to, _) in edges {
                if reachable[to] {
                    continue;
                }
                let cap = capacity[from][to];
                if cap > Zero::zero() {
                    cuts.push(((from, to), cap));
                }
            }
        }

        (flows, total, cuts)
    }
}

impl<C: Copy> IndexedGraph<C> {
    /// Build a directed indexed graph from a square adjacency matrix.
    ///
    /// Every `Some(weight)` cell becomes a directed edge from the row index to the
    /// column index. `None` cells produce no edge.
    ///
    /// # Errors
    ///
    /// Returns [`IndexedInputError::RaggedMatrix`] if rows have different lengths and
    /// [`IndexedInputError::NonSquareAdjacencyMatrix`] if the matrix is not square.
    ///
    /// # Example
    ///
    /// ```
    /// use pathfinding_indexed::IndexedGraph;
    ///
    /// let graph = IndexedGraph::from_adjacency_matrix(&[
    ///     vec![None, Some(3), None],
    ///     vec![None, None, Some(2)],
    ///     vec![Some(1), None, None],
    /// ])
    /// .unwrap();
    ///
    /// assert_eq!(graph.successors(0), &[(1, 3)]);
    /// assert_eq!(graph.successors(1), &[(2, 2)]);
    /// assert_eq!(graph.successors(2), &[(0, 1)]);
    /// ```
    pub fn from_adjacency_matrix(matrix: &[Vec<Option<C>>]) -> Result<Self, IndexedInputError> {
        let rows = validate_rectangular_matrix(matrix)?;
        if rows != matrix.first().map_or(0, Vec::len) {
            return Err(IndexedInputError::NonSquareAdjacencyMatrix);
        }

        let adjacency = matrix
            .iter()
            .map(|row| {
                row.iter()
                    .enumerate()
                    .filter_map(|(column, weight)| weight.map(|cost| (column, cost)))
                    .collect()
            })
            .collect();
        Ok(Self::from_adjacency(adjacency))
    }
}

/// An undirected graph stored as dense `usize` indices with weighted adjacency lists.
#[derive(Clone, Debug)]
pub struct IndexedUndirectedGraph<C> {
    adjacency: Vec<Vec<(usize, C)>>,
    edges: Vec<(usize, usize, C)>,
}

impl<C> IndexedUndirectedGraph<C> {
    /// Build an undirected indexed graph from a list of edges.
    #[must_use]
    pub fn from_edges(node_count: usize, edges: Vec<(usize, usize, C)>) -> Self
    where
        C: Clone,
    {
        let mut adjacency = vec![Vec::new(); node_count];
        for (u, v, w) in &edges {
            debug_assert!(*u < node_count, "edge start out of bounds");
            debug_assert!(*v < node_count, "edge end out of bounds");
            adjacency[*u].push((*v, w.clone()));
            adjacency[*v].push((*u, w.clone()));
        }
        Self { adjacency, edges }
    }

    /// Return the number of nodes in the graph.
    #[must_use]
    pub const fn node_count(&self) -> usize {
        self.adjacency.len()
    }

    /// Return the adjacency list for `node`.
    #[must_use]
    pub fn successors(&self, node: usize) -> &[(usize, C)] {
        &self.adjacency[node]
    }

    /// Return the canonical edge list (each edge appears once).
    #[must_use]
    pub fn edges(&self) -> &[(usize, usize, C)] {
        &self.edges
    }

    /// Return all adjacency lists.
    #[must_use]
    pub fn adjacency(&self) -> &[Vec<(usize, C)>] {
        &self.adjacency
    }

    /// Compute connected components of the graph.
    #[must_use]
    pub fn connected_components(&self) -> Vec<Vec<usize>> {
        let nodes = (0..self.node_count()).collect::<Vec<_>>();
        let components =
            crate::undirected::connected_components::connected_components(&nodes, |n| {
                self.successors(*n).iter().map(|edge| edge.0)
            });
        components
            .into_iter()
            .map(|set| set.into_iter().collect())
            .collect()
    }

    /// Return the component index for each node.
    #[must_use]
    pub fn component_index(&self) -> Vec<usize> {
        let components = self.connected_components();
        let mut index = vec![usize::MAX; self.node_count()];
        for (component_idx, component) in components.iter().enumerate() {
            for &node in component {
                index[node] = component_idx;
            }
        }
        index
    }

    /// Return connected components (alias of [`Self::connected_components`]).
    #[must_use]
    pub fn components(&self) -> Vec<Vec<usize>> {
        self.connected_components()
    }

    /// Separate connected components using neighbor groups derived from adjacency.
    #[must_use]
    pub fn separate_components(&self) -> (Vec<usize>, Vec<usize>) {
        let groups = (0..self.node_count())
            .map(|node| {
                let mut group = Vec::with_capacity(self.adjacency[node].len() + 1);
                group.push(node);
                group.extend(self.adjacency[node].iter().map(|edge| edge.0));
                group
            })
            .collect::<Vec<_>>();
        let (mapping, group_indices) =
            crate::undirected::connected_components::separate_components(&groups);
        let mut node_components = vec![usize::MAX; self.node_count()];
        for (node, component) in mapping {
            node_components[*node] = component;
        }
        (node_components, group_indices)
    }

    /// Enumerate all maximal cliques and collect them into a vector.
    #[must_use]
    pub fn maximal_cliques_collect(&self) -> Vec<Vec<usize>> {
        let adjacency_sets = self.adjacency_sets();
        let mut connected = |a: &usize, b: &usize| adjacency_sets[*a].contains(b);
        crate::undirected::cliques::maximal_cliques_collect(0..self.node_count(), &mut connected)
            .into_iter()
            .map(|set| set.into_iter().collect())
            .collect()
    }

    /// Enumerate all maximal cliques and send them to `consumer`.
    pub fn maximal_cliques<CO>(&self, mut consumer: CO)
    where
        CO: FnMut(&Vec<usize>),
    {
        let adjacency_sets = self.adjacency_sets();
        let mut connected = |a: &usize, b: &usize| adjacency_sets[*a].contains(b);
        let mut adapter = |clique: &std::collections::HashSet<usize>| {
            let clique_vec = clique.iter().copied().collect::<Vec<_>>();
            consumer(&clique_vec);
        };
        crate::undirected::cliques::maximal_cliques(
            0..self.node_count(),
            &mut connected,
            &mut adapter,
        );
    }

    /// Compute a minimum spanning tree using Kruskal's algorithm (collected).
    #[must_use]
    pub fn kruskal(&self) -> Vec<(usize, usize, C)>
    where
        C: Clone + Ord,
    {
        self.kruskal_indices().collect()
    }

    /// Compute a minimum spanning tree using Kruskal's algorithm (iterator).
    pub fn kruskal_indices(&self) -> impl Iterator<Item = (usize, usize, C)>
    where
        C: Clone + Ord,
    {
        crate::undirected::kruskal::kruskal_indices(self.node_count(), self.edges())
    }

    /// Compute a minimum spanning tree using Prim's algorithm.
    #[must_use]
    pub fn prim(&self) -> Vec<(usize, usize, C)>
    where
        C: Clone + Ord,
    {
        crate::undirected::prim::prim(self.edges())
            .into_iter()
            .map(|(a, b, c)| (*a, *b, c))
            .collect()
    }

    fn adjacency_sets(&self) -> Vec<FxHashSet<usize>> {
        self.adjacency
            .iter()
            .map(|edges| edges.iter().map(|edge| edge.0).collect())
            .collect()
    }
}

/// Helper that maps external node values to dense indices and builds an indexed graph.
#[derive(Clone, Debug)]
pub struct IndexedGraphMap<N, C> {
    graph: IndexedGraph<C>,
    nodes: Vec<N>,
    index: FxHashMap<N, usize>,
}

impl<N, C> IndexedGraphMap<N, C>
where
    N: Eq + Hash + Clone,
{
    /// Build a mapped graph from seed nodes and a successor function.
    pub fn from_nodes_and_successors<I, FN, IN>(nodes: I, mut successors: FN) -> Self
    where
        I: IntoIterator<Item = N>,
        FN: FnMut(&N) -> IN,
        IN: IntoIterator<Item = (N, C)>,
    {
        let mut mapped = Self {
            graph: IndexedGraph::from_adjacency(Vec::new()),
            nodes: Vec::new(),
            index: FxHashMap::default(),
        };

        for node in nodes {
            mapped.ensure_index(node);
        }

        let mut cursor = 0usize;
        while cursor < mapped.nodes.len() {
            let node = mapped.nodes[cursor].clone();
            let mut edges = Vec::new();
            for (neighbor, cost) in successors(&node) {
                let neighbor_idx = mapped.ensure_index(neighbor);
                edges.push((neighbor_idx, cost));
            }
            if cursor >= mapped.graph.adjacency.len() {
                mapped.graph.adjacency.push(edges);
            } else {
                mapped.graph.adjacency[cursor] = edges;
            }
            cursor += 1;
        }

        mapped
    }

    /// Return the indexed graph.
    #[must_use]
    pub const fn graph(&self) -> &IndexedGraph<C> {
        &self.graph
    }

    /// Return the indexed graph, consuming the mapping helper.
    #[must_use]
    pub fn into_graph(self) -> IndexedGraph<C> {
        self.graph
    }

    /// Return the number of nodes in the mapped graph.
    #[must_use]
    pub const fn node_count(&self) -> usize {
        self.graph.node_count()
    }

    /// Return the index assigned to `node`.
    #[must_use]
    pub fn index_of(&self, node: &N) -> Option<usize> {
        self.index.get(node).copied()
    }

    /// Return the external node value for a given index.
    #[must_use]
    pub fn node(&self, index: usize) -> Option<&N> {
        self.nodes.get(index)
    }

    /// Return the mapped node values in index order.
    #[must_use]
    pub fn nodes(&self) -> &[N] {
        &self.nodes
    }

    fn ensure_index(&mut self, node: N) -> usize {
        if let Some(&idx) = self.index.get(&node) {
            return idx;
        }
        let idx = self.nodes.len();
        self.nodes.push(node.clone());
        self.index.insert(node, idx);
        self.graph.adjacency.push(Vec::new());
        idx
    }
}

impl IndexedGraphMap<(usize, usize), usize> {
    /// Build a mapped graph from a boolean matrix with 4-neighbor connectivity.
    ///
    /// `true` cells are walkable and become nodes labeled by `(row, column)`.
    ///
    /// # Errors
    ///
    /// Returns [`IndexedInputError::RaggedMatrix`] if rows have different lengths.
    ///
    /// # Example
    ///
    /// ```
    /// use pathfinding_indexed::IndexedGraphMap;
    ///
    /// let mapped = IndexedGraphMap::from_walkable_matrix_4(&[
    ///     vec![true, true, false],
    ///     vec![false, true, true],
    /// ])
    /// .unwrap();
    ///
    /// let start = mapped.index_of(&(0, 0)).unwrap();
    /// let goal = mapped.index_of(&(1, 2)).unwrap();
    /// let result = mapped.graph().dijkstra(start, |node| node == goal);
    /// assert_eq!(result.map(|(_, cost)| cost), Some(3));
    /// ```
    pub fn from_walkable_matrix_4(matrix: &[Vec<bool>]) -> Result<Self, IndexedInputError> {
        Self::from_walkable_matrix(matrix, false)
    }

    /// Build a mapped graph from a boolean matrix with 8-neighbor connectivity.
    ///
    /// `true` cells are walkable and become nodes labeled by `(row, column)`.
    ///
    /// # Errors
    ///
    /// Returns [`IndexedInputError::RaggedMatrix`] if rows have different lengths.
    pub fn from_walkable_matrix_8(matrix: &[Vec<bool>]) -> Result<Self, IndexedInputError> {
        Self::from_walkable_matrix(matrix, true)
    }

    /// Build a mapped graph from grid dimensions and a walkability predicate using
    /// 4-neighbor connectivity.
    pub fn from_walkable_cells_4<F>(rows: usize, columns: usize, walkable: F) -> Self
    where
        F: FnMut((usize, usize)) -> bool,
    {
        Self::from_walkable_cells(rows, columns, false, walkable)
    }

    /// Build a mapped graph from grid dimensions and a walkability predicate using
    /// 8-neighbor connectivity.
    pub fn from_walkable_cells_8<F>(rows: usize, columns: usize, walkable: F) -> Self
    where
        F: FnMut((usize, usize)) -> bool,
    {
        Self::from_walkable_cells(rows, columns, true, walkable)
    }

    fn from_walkable_matrix(
        matrix: &[Vec<bool>],
        diagonal_mode: bool,
    ) -> Result<Self, IndexedInputError> {
        let rows = validate_rectangular_matrix(matrix)?;
        let columns = matrix.first().map_or(0, Vec::len);
        Ok(Self::from_walkable_cells(
            rows,
            columns,
            diagonal_mode,
            |(row, column)| matrix[row][column],
        ))
    }

    fn from_walkable_cells<F>(
        rows: usize,
        columns: usize,
        diagonal_mode: bool,
        mut walkable: F,
    ) -> Self
    where
        F: FnMut((usize, usize)) -> bool,
    {
        let mut nodes = Vec::new();
        let mut index = FxHashMap::default();
        let mut cell_index = vec![vec![None; columns]; rows];

        for (row, row_indices) in cell_index.iter_mut().enumerate() {
            for (column, slot) in row_indices.iter_mut().enumerate() {
                let cell = (row, column);
                if !walkable(cell) {
                    continue;
                }
                let node_index = nodes.len();
                nodes.push(cell);
                index.insert(cell, node_index);
                *slot = Some(node_index);
            }
        }

        let mut adjacency = vec![Vec::new(); nodes.len()];
        for (row, row_indices) in cell_index.iter().enumerate() {
            for (column, &node_index) in row_indices.iter().enumerate() {
                let Some(node_index) = node_index else {
                    continue;
                };
                append_neighbor(&mut adjacency[node_index], &cell_index, row, column, -1, 0);
                append_neighbor(&mut adjacency[node_index], &cell_index, row, column, 1, 0);
                append_neighbor(&mut adjacency[node_index], &cell_index, row, column, 0, -1);
                append_neighbor(&mut adjacency[node_index], &cell_index, row, column, 0, 1);
                if diagonal_mode {
                    append_neighbor(&mut adjacency[node_index], &cell_index, row, column, -1, -1);
                    append_neighbor(&mut adjacency[node_index], &cell_index, row, column, -1, 1);
                    append_neighbor(&mut adjacency[node_index], &cell_index, row, column, 1, -1);
                    append_neighbor(&mut adjacency[node_index], &cell_index, row, column, 1, 1);
                }
            }
        }

        Self {
            graph: IndexedGraph::from_adjacency(adjacency),
            nodes,
            index,
        }
    }
}

fn validate_rectangular_matrix<T>(matrix: &[Vec<T>]) -> Result<usize, IndexedInputError> {
    let expected = matrix.first().map_or(0, Vec::len);
    if matrix.iter().any(|row| row.len() != expected) {
        return Err(IndexedInputError::RaggedMatrix);
    }
    Ok(matrix.len())
}

fn append_neighbor(
    edges: &mut Vec<(usize, usize)>,
    cell_index: &[Vec<Option<usize>>],
    row: usize,
    column: usize,
    row_delta: isize,
    column_delta: isize,
) {
    let Some(next_row) = row.checked_add_signed(row_delta) else {
        return;
    };
    let Some(next_column) = column.checked_add_signed(column_delta) else {
        return;
    };
    let Some(target_row) = cell_index.get(next_row) else {
        return;
    };
    let Some(Some(target)) = target_row.get(next_column) else {
        return;
    };
    edges.push((*target, 1));
}

#[cfg(test)]
mod tests {
    use super::{IndexedGraph, IndexedGraphMap, IndexedInputError};

    #[test]
    fn adjacency_matrix_builds_expected_edges() {
        let graph = IndexedGraph::from_adjacency_matrix(&[
            vec![None, Some(4), None],
            vec![Some(2), None, Some(7)],
            vec![None, None, None],
        ])
        .unwrap();

        assert_eq!(graph.successors(0), &[(1, 4)]);
        assert_eq!(graph.successors(1), &[(0, 2), (2, 7)]);
        assert_eq!(graph.successors(2), &[]);
    }

    #[test]
    fn adjacency_matrix_rejects_non_square_input() {
        let err = IndexedGraph::from_adjacency_matrix(&[vec![None, Some(1)]]).unwrap_err();
        assert_eq!(err, IndexedInputError::NonSquareAdjacencyMatrix);
    }

    #[test]
    fn walkable_matrix_4_maps_coordinates() {
        let mapped = IndexedGraphMap::from_walkable_matrix_4(&[
            vec![true, true, false],
            vec![false, true, true],
        ])
        .unwrap();

        assert_eq!(mapped.node_count(), 4);
        let start = mapped.index_of(&(0, 0)).unwrap();
        let goal = mapped.index_of(&(1, 2)).unwrap();
        let result = mapped.graph().dijkstra(start, |node| node == goal);
        assert_eq!(result.map(|(_, cost)| cost), Some(3));
    }

    #[test]
    fn walkable_matrix_8_adds_diagonal_edges() {
        let mapped =
            IndexedGraphMap::from_walkable_matrix_8(&[vec![true, false], vec![false, true]])
                .unwrap();

        let start = mapped.index_of(&(0, 0)).unwrap();
        let goal = mapped.index_of(&(1, 1)).unwrap();
        assert_eq!(mapped.graph().successors(start), &[(goal, 1)]);
    }

    #[test]
    fn walkable_matrix_rejects_ragged_input() {
        let err =
            IndexedGraphMap::from_walkable_matrix_4(&[vec![true, true], vec![true]]).unwrap_err();
        assert_eq!(err, IndexedInputError::RaggedMatrix);
    }

    #[test]
    fn walkable_cells_helper_uses_predicate() {
        let mapped = IndexedGraphMap::from_walkable_cells_4(2, 3, |cell| {
            matches!(cell, (0, 0) | (0, 1) | (1, 1))
        });

        assert_eq!(mapped.node_count(), 3);
        assert!(mapped.index_of(&(1, 2)).is_none());
    }
}