yagraphc 0.1.2

Crate for working with Graph data structures and common algorithms on top of it.
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
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
//! Traits that correspond to the main functionalities of the crate.
//!
//! `Graph` is the main trait for working with general graph traversal, such as
//! BFS and DFS.
//!
//! `ArithmeticallyWeightedGraph` is the main trait for working with path finding,
//! such as Dijkstra's algorithm or A*. It is also intended to handle more general
//! algorithms that rely on arithmetical weights in the future.
use std::collections::BinaryHeap;
use std::collections::HashMap;
use std::collections::HashSet;
use std::collections::VecDeque;
use std::hash::Hash;

use thiserror::Error;

#[derive(Error, Debug)]
#[error("node not found")]
pub struct NodeNotFound;

pub struct BfsIter<'a, T, W> {
    pub(crate) queue: VecDeque<(T, usize)>,
    pub(crate) visited: HashSet<T>,
    pub(crate) graph: &'a dyn Traversable<T, W>,
}

impl<'a, T, W> Iterator for BfsIter<'a, T, W>
where
    T: Clone + Copy + Hash + PartialEq + Eq,
    W: Clone + Copy,
{
    type Item = (T, usize);

    fn next(&mut self) -> Option<Self::Item> {
        while let Some((node, depth)) = self.queue.pop_front() {
            if self.visited.contains(&node) {
                continue;
            }

            self.visited.insert(node);

            for (next, _) in self.graph.edges(&node) {
                if self.visited.contains(&next) {
                    continue;
                } else {
                    self.queue.push_back((next, depth + 1))
                }
            }

            return Some((node, depth));
        }
        None
    }
}

pub struct DfsIter<'a, T, W> {
    pub(crate) queue: VecDeque<(T, usize)>,
    pub(crate) visited: HashSet<T>,
    pub(crate) graph: &'a dyn Traversable<T, W>,
}

impl<'a, T, W> Iterator for DfsIter<'a, T, W>
where
    T: Clone + Copy + Hash + PartialEq + Eq,
    W: Clone + Copy,
{
    type Item = (T, usize);

    fn next(&mut self) -> Option<Self::Item> {
        while let Some((node, depth)) = self.queue.pop_front() {
            if self.visited.contains(&node) {
                continue;
            }

            self.visited.insert(node);

            for (next, _) in self.graph.edges(&node) {
                if self.visited.contains(&next) {
                    continue;
                } else {
                    self.queue.push_front((next, depth + 1))
                }
            }

            return Some((node, depth));
        }

        None
    }
}

pub struct PostOrderDfsIter<T> {
    pub(crate) queue: VecDeque<(T, usize)>,
}

impl<'a, T> PostOrderDfsIter<T>
where
    T: Clone + Copy + Hash + PartialEq + Eq,
{
    pub fn new<W>(graph: &'a dyn Traversable<T, W>, from: T) -> Self
    where
        W: Clone + Copy,
    {
        let mut queue = VecDeque::new();
        let mut visited = HashSet::new();

        dfs_post_order(graph, from, 0, &mut queue, &mut visited);

        Self { queue }
    }
}

fn dfs_post_order<T, W>(
    graph: &dyn Traversable<T, W>,
    node: T,
    depth: usize,
    queue: &mut VecDeque<(T, usize)>,
    visited: &mut HashSet<T>,
) where
    T: Clone + Copy + Hash + PartialEq + Eq,
    W: Clone + Copy,
{
    visited.insert(node);
    for (next, _) in graph.edges(&node) {
        if visited.contains(&next) {
            continue;
        }

        dfs_post_order(graph, next, depth + 1, queue, visited);
    }

    queue.push_back((node, depth));
}

impl<T> Iterator for PostOrderDfsIter<T>
where
    T: Clone + Copy + Hash + PartialEq + Eq,
{
    type Item = (T, usize);

    fn next(&mut self) -> Option<Self::Item> {
        self.queue.pop_front()
    }
}

pub struct NodeIter<'a, T> {
    pub(crate) nodes_iter: std::collections::hash_set::Iter<'a, T>,
}

impl<T> Iterator for NodeIter<'_, T>
where
    T: Clone + Copy,
{
    type Item = T;
    fn next(&mut self) -> Option<Self::Item> {
        self.nodes_iter.next().copied()
    }
}

pub enum EdgeIterType<'a, T, W> {
    EdgeIter(EdgeIter<'a, T, W>),
    EdgeIterVec(EdgeIterVec<'a, T, W>),
}

impl<'a, T, W> Iterator for EdgeIterType<'a, T, W>
where
    T: Clone + Copy,
    W: Clone + Copy,
{
    type Item = (T, W);
    fn next(&mut self) -> Option<Self::Item> {
        match self {
            EdgeIterType::EdgeIter(iter) => iter.next(),
            EdgeIterType::EdgeIterVec(iter) => iter.next(),
        }
    }
}

pub struct EdgeIter<'a, T, W> {
    pub(crate) edge_iter: std::collections::hash_map::Iter<'a, T, W>,
}

impl<T, W> Iterator for EdgeIter<'_, T, W>
where
    T: Clone + Copy,
    W: Clone + Copy,
{
    type Item = (T, W);
    fn next(&mut self) -> Option<Self::Item> {
        self.edge_iter.next().map(copy_tuple)
    }
}

pub struct EdgeIterVec<'a, T, W> {
    pub(crate) edge_iter: core::slice::Iter<'a, (T, W)>,
}

impl<T, W> Iterator for EdgeIterVec<'_, T, W>
where
    T: Clone + Copy,
    W: Clone + Copy,
{
    type Item = (T, W);
    fn next(&mut self) -> Option<Self::Item> {
        self.edge_iter.next().copied()
    }
}

pub trait GraphBuilding<T, W>
where
    T: Clone + Copy + Eq + Hash + PartialEq,
    W: Clone + Copy,
{
    fn add_edge(&mut self, from: T, to: T, weight: W);

    fn add_node(&mut self, node: T) -> bool;

    fn remove_edge(&mut self, from: T, to: T) -> Result<(), NodeNotFound>;

    fn remove_node(&mut self, node: T) -> Result<(), NodeNotFound>;

    fn has_edge(&self, from: T, to: T) -> bool;
}

pub trait Traversable<T, W>
where
    T: Clone + Copy + Eq + Hash + PartialEq,
    W: Clone + Copy,
{
    /// Iterates over edges of the node as the target nodes and the edge weight.
    ///
    /// If the graph is undirected, should return the nodes that are connected to it by
    /// an edge.
    ///
    /// If the graph is directed, should return the outbound nodes.
    ///
    /// # Examples
    /// ```rust
    /// use yagraphc::graph::{UnGraph, DiGraph};
    /// use yagraphc::graph::traits::{GraphBuilding, Traversable};
    ///
    /// let mut graph = UnGraph::default();
    ///
    /// graph.add_edge(1, 2, ());
    /// graph.add_edge(2, 3, ());
    ///
    /// let edges = graph.edges(&2);
    ///
    /// assert_eq!(edges.count(), 2);
    ///
    /// let mut graph = DiGraph::default();
    ///
    /// graph.add_edge(1, 2, ());
    /// graph.add_edge(2, 3, ());
    ///
    /// let edges = graph.edges(&2);
    ///
    /// assert_eq!(edges.count(), 1);
    fn edges(&self, n: &T) -> EdgeIterType<T, W>;

    fn edge_weight(&self, from: T, to: T) -> Result<W, NodeNotFound>;

    /// Iterates over inbound-edges of the node as the target nodes and the edge weight.
    ///
    /// If the graph is undirected, should return the nodes that are connected to it by
    /// an edge. Thus, it is equivalent to `edges` in that case.
    ///
    /// If the graph is directed, should return the inbound nodes.
    ///
    /// # Examples
    /// ```rust
    /// use yagraphc::graph::{UnGraph, DiGraph};
    /// use yagraphc::graph::traits::{GraphBuilding, Traversable};
    ///
    /// let mut graph = UnGraph::default();
    ///
    /// graph.add_edge(1, 2, ());
    /// graph.add_edge(2, 3, ());
    /// graph.add_edge(4, 2, ());
    ///
    /// let edges = graph.in_edges(&2);
    ///
    /// assert_eq!(edges.count(), 3);
    ///
    /// let mut graph = DiGraph::default();
    ///
    /// graph.add_edge(1, 2, ());
    /// graph.add_edge(2, 3, ());
    /// graph.add_edge(4, 2, ());
    ///
    /// let edges = graph.in_edges(&2);
    ///
    /// assert_eq!(edges.count(), 2);
    fn in_edges(&self, n: &T) -> EdgeIterType<T, W>;

    /// Returns an iterator over all nodes.
    ///
    /// # Examples
    /// ```rust
    /// use yagraphc::graph::UnGraph;
    /// use yagraphc::graph::traits::{GraphBuilding, Traversable};
    ///
    /// let mut graph = UnGraph::default();
    ///
    /// graph.add_edge(1, 2, ());
    /// graph.add_edge(2, 3, ());
    ///
    /// graph.add_node(4);
    ///
    /// assert_eq!(graph.nodes().count(), 4);
    ///
    /// graph.add_node(2);
    /// assert_eq!(graph.nodes().count(), 4);
    fn nodes(&self) -> NodeIter<T>;

    /// Returns an iterator of nodes in breadth-first order.
    ///
    /// Iterator includes the depth at which the nodes were found. Nodes at the
    /// same depth might be randomly shuffled.
    ///
    /// # Examples
    /// ```
    /// use yagraphc::graph::UnGraph;
    /// use yagraphc::graph::traits::{GraphBuilding, Traversable};
    ///
    /// let mut graph = UnGraph::new();
    ///
    /// graph.add_edge(1, 2, ());
    /// graph.add_edge(1, 3, ());
    /// graph.add_edge(2, 4, ());
    /// graph.add_edge(2, 5, ());
    ///
    /// let bfs = graph.bfs(1);
    ///
    /// let depths = bfs.map(|(_, depth)| depth).collect::<Vec<_>>();
    ///
    /// assert_eq!(depths, vec![0, 1, 1, 2, 2]);
    fn bfs(&self, from: T) -> BfsIter<T, W>
    where
        Self: Sized,
    {
        let visited = HashSet::new();

        let mut queue = VecDeque::new();
        queue.push_front((from, 0));

        BfsIter {
            queue,
            visited,
            graph: self,
        }
    }

    /// Returns an iterator of nodes in depth-first order, in pre-order.
    ///
    /// Iterator includes the depth at which the nodes were found. Order is not
    /// deterministic.
    ///
    /// # Examples
    /// ```
    /// use yagraphc::graph::UnGraph;
    /// use yagraphc::graph::traits::{GraphBuilding, Traversable};
    ///
    /// let mut graph = UnGraph::new();
    ///
    /// graph.add_edge(1, 2, ());
    /// graph.add_edge(2, 3, ());
    /// graph.add_edge(3, 4, ());
    /// graph.add_edge(1, 5, ());
    /// graph.add_edge(5, 6, ());
    ///
    /// let dfs = graph.dfs(1);
    ///
    /// let depths = dfs.map(|(node, _)| node).collect::<Vec<_>>();
    ///
    /// assert!(matches!(depths[..], [1, 2, 3, 4, 5, 6] | [1, 5, 6, 2, 3, 4]));
    fn dfs(&self, from: T) -> DfsIter<T, W>
    where
        Self: Sized,
    {
        let visited = HashSet::new();

        let mut queue = VecDeque::new();
        queue.push_front((from, 0));

        DfsIter {
            queue,
            visited,
            graph: self,
        }
    }

    /// Returns an iterator of nodes in depth-first order, in post-order.
    ///
    /// Iterator includes the depth at which the nodes were found. Order is not
    /// deterministic.
    ///
    /// Currently implemented recursively. To be changed to a non-recursive
    /// implemented at some point.
    ///
    /// # Examples
    /// ```
    /// use yagraphc::graph::UnGraph;
    /// use yagraphc::graph::traits::{GraphBuilding, Traversable};
    ///
    /// let mut graph = UnGraph::new();
    ///
    /// graph.add_edge(1, 2, ());
    /// graph.add_edge(2, 3, ());
    /// graph.add_edge(3, 4, ());
    /// graph.add_edge(1, 5, ());
    /// graph.add_edge(5, 6, ());
    ///
    /// let dfs = graph.dfs_post_order(1);
    ///
    /// let depths = dfs.map(|(node, _)| node).collect::<Vec<_>>();
    ///
    /// assert!(matches!(depths[..], [6, 5, 4, 3, 2, 1] | [4, 3, 2, 6, 5, 1]));
    // TODO: Implement post-order non-recursively.
    fn dfs_post_order(&self, from: T) -> PostOrderDfsIter<T>
    where
        Self: Sized,
    {
        PostOrderDfsIter::new(self, from)
    }

    /// Finds path from `from` to `to` using BFS.
    ///
    /// Returns `None` if there is no path.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use yagraphc::graph::UnGraph;
    /// use yagraphc::graph::traits::{GraphBuilding, Traversable};
    ///
    /// let mut graph = UnGraph::new();
    ///
    /// graph.add_edge(1, 2, ());
    /// graph.add_edge(2, 3, ());
    /// graph.add_edge(3, 4, ());
    /// graph.add_edge(1, 5, ());
    /// graph.add_edge(5, 6, ());
    ///
    /// let path = graph.find_path(1, 4);
    ///
    /// assert_eq!(path, Some(vec![1, 2, 3, 4]));
    fn find_path(&self, from: T, to: T) -> Option<Vec<T>>
    where
        Self: Sized,
    {
        let mut visited = HashSet::new();
        let mut pairs = HashMap::new();
        let mut queue = VecDeque::new();

        queue.push_back((from, from));

        while let Some((prev, current)) = queue.pop_front() {
            if visited.contains(&current) {
                continue;
            }
            visited.insert(current);
            pairs.insert(current, prev);

            if current == to {
                let mut node = current;

                let mut path = Vec::new();
                while node != from {
                    path.push(node);

                    node = pairs[&node];
                }

                path.push(from);

                path.reverse();

                return Some(path);
            }

            for (target, _) in self.edges(&current) {
                if visited.contains(&target) {
                    continue;
                }

                queue.push_back((current, target));
            }
        }

        None
    }

    /// Finds path from `from` to `to` using BFS while filtering edges.
    ///
    /// Returns `None` if there is no path.
    ///
    /// For an undirected graph, strive to make predicate(x,y) == predicate(y,x).
    /// As of now, the order is related to the exploration direction of bfs,
    /// but it is advisable not to rely on direction concepts on undirected graphs.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use yagraphc::graph::UnGraph;
    /// use yagraphc::graph::traits::{GraphBuilding, Traversable};
    /// let mut graph = UnGraph::default();

    /// graph.add_edge(1, 2, ());
    /// graph.add_edge(2, 3, ());
    /// graph.add_edge(3, 4, ());
    /// graph.add_edge(4, 5, ());

    /// graph.add_edge(1, 7, ());
    /// graph.add_edge(7, 5, ());

    /// let path = graph.find_path(1, 5).unwrap();

    /// assert_eq!(path, vec![1, 7, 5]);

    /// let path = graph
    ///     .find_path_filter_edges(1, 5, |x, y| (x, y) != (1, 7))
    ///     .unwrap();

    /// assert_eq!(path, vec![1, 2, 3, 4, 5]);
    fn find_path_filter_edges<G>(&self, from: T, to: T, predicate: G) -> Option<Vec<T>>
    where
        Self: Sized,
        G: Fn(T, T) -> bool,
    {
        let mut visited = HashSet::new();
        let mut pairs = HashMap::new();
        let mut queue = VecDeque::new();

        queue.push_back((from, from));

        while let Some((prev, current)) = queue.pop_front() {
            if visited.contains(&current) {
                continue;
            }
            visited.insert(current);
            pairs.insert(current, prev);

            if current == to {
                let mut node = current;

                let mut path = Vec::new();
                while node != from {
                    path.push(node);

                    node = pairs[&node];
                }

                path.push(from);

                path.reverse();

                return Some(path);
            }

            for (target, _) in self.edges(&current) {
                if visited.contains(&target) || !predicate(current, target) {
                    continue;
                }

                queue.push_back((current, target));
            }
        }

        None
    }

    /// Returns a list of connected components of the graph.
    ///
    /// If being used in a directed graph, those are the strongly connected components,
    /// computed using Kosaraju's algorithm.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use yagraphc::graph::{UnGraph, DiGraph};
    /// use yagraphc::graph::traits::{GraphBuilding, Traversable};
    ///
    /// let mut graph = UnGraph::new();
    ///
    /// graph.add_edge(1, 2, ());
    /// graph.add_edge(2, 3, ());
    ///
    /// graph.add_edge(4, 5, ());
    /// graph.add_edge(5, 6, ());
    /// graph.add_edge(6, 4, ());
    ///
    /// let components = graph.connected_components();
    ///
    /// assert_eq!(components.len(), 2);
    ///
    /// let mut graph = DiGraph::new();
    ///
    /// graph.add_edge(1, 2, ());
    /// graph.add_edge(2, 3, ());
    ///
    /// graph.add_edge(4, 5, ());
    /// graph.add_edge(5, 6, ());
    /// graph.add_edge(6, 4, ());
    ///
    /// let components = graph.connected_components();
    ///
    /// assert_eq!(components.len(), 4);
    fn connected_components(&self) -> Vec<Vec<T>>
    where
        Self: Sized,
    {
        let mut visited = HashSet::new();
        let mut stack = Vec::new();

        for node in self.nodes() {
            if visited.contains(&node) {
                continue;
            }

            for (inner_node, _) in self.dfs_post_order(node) {
                visited.insert(inner_node);
                stack.push(inner_node);
            }
        }

        stack.reverse();

        let mut visited = HashSet::new();
        let mut components = Vec::new();

        for node in stack {
            if visited.contains(&node) {
                continue;
            }

            let mut component = Vec::new();

            let mut stack = Vec::new();
            stack.push(node);

            while let Some(node) = stack.pop() {
                if visited.contains(&node) {
                    continue;
                }

                component.push(node);
                visited.insert(node);

                for (inner_node, _) in self.in_edges(&node) {
                    stack.push(inner_node);
                }
            }

            components.push(component);
        }

        components
    }
}

fn copy_tuple<T, W>(x: (&T, &W)) -> (T, W)
where
    T: Clone + Copy,
    W: Clone + Copy,
{
    (*x.0, *x.1)
}

struct QueueEntry<T, W>
where
    T: Clone + Copy,
    W: Ord + PartialOrd,
{
    pub node: T,
    pub cur_cost: W,
}

impl<T, W> Ord for QueueEntry<T, W>
where
    T: Clone + Copy,
    W: Ord + PartialOrd,
{
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        other.cur_cost.cmp(&self.cur_cost)
    }
}

impl<T, W> PartialOrd for QueueEntry<T, W>
where
    T: Clone + Copy,
    W: Ord + PartialOrd,
{
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl<T, W> PartialEq for QueueEntry<T, W>
where
    T: Clone + Copy,
    W: Ord + PartialOrd,
{
    fn eq(&self, other: &Self) -> bool {
        self.cur_cost.eq(&other.cur_cost)
    }
}

impl<T, W> Eq for QueueEntry<T, W>
where
    T: Clone + Copy,
    W: Ord + PartialOrd,
{
}

pub trait ArithmeticallyWeightedGraph<T, W>
where
    T: Clone + Copy + Eq + Hash + PartialEq,
    W: Clone
        + Copy
        + std::ops::Add<Output = W>
        + std::ops::Sub<Output = W>
        + PartialOrd
        + Ord
        + Default,
{
    /// Returns the shortest length among paths from `from` to `to`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use yagraphc::graph::UnGraph;
    /// use yagraphc::graph::traits::{GraphBuilding, Traversable};
    /// use yagraphc::graph::traits::ArithmeticallyWeightedGraph;
    ///
    /// let mut graph = UnGraph::new();
    ///
    /// graph.add_edge(1, 2, 1);
    /// graph.add_edge(2, 3, 2);
    /// graph.add_edge(3, 4, 3);
    /// graph.add_edge(1, 4, 7);
    ///
    /// assert_eq!(graph.dijkstra(1, 4), Some(6));
    /// assert_eq!(graph.dijkstra(1, 5), None);
    fn dijkstra(&self, from: T, to: T) -> Option<W>
    where
        Self: Traversable<T, W>,
    {
        let mut visited = HashSet::new();
        let mut distances = HashMap::new();

        distances.insert(from, W::default());

        let mut queue = BinaryHeap::new();
        queue.push(QueueEntry {
            node: from,
            cur_cost: W::default(),
        });

        while let Some(QueueEntry {
            node,
            cur_cost: cur_dist,
        }) = queue.pop()
        {
            if visited.contains(&node) {
                continue;
            }

            if node == to {
                return Some(cur_dist);
            }

            for (target, weight) in self.edges(&node) {
                let mut distance = cur_dist + weight;

                distances
                    .entry(target)
                    .and_modify(|dist| {
                        let best_dist = (*dist).min(cur_dist + weight);

                        distance = best_dist;
                        *dist = best_dist;
                    })
                    .or_insert(cur_dist + weight);

                if !visited.contains(&target) {
                    queue.push(QueueEntry {
                        node: target,
                        cur_cost: distance,
                    })
                }
            }

            visited.insert(node);
        }

        None
    }

    /// Returns the shortest path among paths from `from` to `to`, together with its length.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use yagraphc::graph::UnGraph;
    /// use yagraphc::graph::traits::{GraphBuilding, Traversable};
    /// use yagraphc::graph::traits::ArithmeticallyWeightedGraph;
    ///
    /// let mut graph = UnGraph::new();
    ///
    /// graph.add_edge(1, 2, 1);
    /// graph.add_edge(2, 3, 2);
    /// graph.add_edge(3, 4, 3);
    /// graph.add_edge(1, 4, 7);
    ///
    /// assert_eq!(graph.dijkstra_with_path(1, 4).unwrap().0, vec![1, 2, 3, 4]);
    /// assert_eq!(graph.dijkstra_with_path(1, 5), None);
    fn dijkstra_with_path(&self, from: T, to: T) -> Option<(Vec<T>, W)>
    where
        Self: Traversable<T, W>,
    {
        let mut visited = HashSet::new();
        let mut distances = HashMap::new();

        distances.insert(from, (W::default(), from));

        let mut queue = BinaryHeap::new();
        queue.push(QueueEntry {
            node: from,
            cur_cost: W::default(),
        });

        while let Some(QueueEntry {
            node,
            cur_cost: cur_dist,
        }) = queue.pop()
        {
            if visited.contains(&node) {
                continue;
            }

            if node == to {
                let mut path = Vec::new();

                let mut node = node;

                while node != from {
                    path.push(node);

                    node = distances[&node].1;
                }

                path.push(from);

                path.reverse();

                return Some((path, cur_dist));
            }

            for (target, weight) in self.edges(&node) {
                distances
                    .entry(target)
                    .and_modify(|(dist, previous)| {
                        if cur_dist + weight < *dist {
                            *dist = cur_dist + weight;
                            *previous = node;
                        }
                    })
                    .or_insert((cur_dist + weight, node));

                if !visited.contains(&target) {
                    queue.push(QueueEntry {
                        node: target,
                        cur_cost: distances[&target].0,
                    })
                }
            }

            visited.insert(node);
        }

        None
    }

    /// Returns the shortest length among paths from `from` to `to` using A*.
    ///
    /// `heuristic` corresponds to the heuristic function of the A* algorithm.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use yagraphc::graph::UnGraph;
    /// use yagraphc::graph::traits::{GraphBuilding, Traversable};
    /// use yagraphc::graph::traits::ArithmeticallyWeightedGraph;
    ///
    /// let mut graph = UnGraph::new();
    ///
    /// graph.add_edge(1, 2, 1);
    /// graph.add_edge(2, 3, 2);
    /// graph.add_edge(3, 4, 3);
    /// graph.add_edge(1, 4, 7);
    ///
    /// assert_eq!(graph.a_star(1, 4, |_| 0), Some(6));
    /// assert_eq!(graph.a_star(1, 5, |_| 0), None);
    fn a_star<G>(&self, from: T, to: T, heuristic: G) -> Option<W>
    where
        Self: Traversable<T, W>,
        G: Fn(T) -> W,
    {
        let mut visited = HashSet::new();
        let mut distances = HashMap::new();

        distances.insert(from, W::default());

        let mut queue = BinaryHeap::new();
        queue.push(QueueEntry {
            node: from,
            cur_cost: W::default() + heuristic(from),
        });

        while let Some(QueueEntry { node, .. }) = queue.pop() {
            if visited.contains(&node) {
                continue;
            }

            if node == to {
                return Some(distances[&node]);
            }

            for (target, weight) in self.edges(&node) {
                let mut distance = distances[&node] + weight;

                distances
                    .entry(target)
                    .and_modify(|dist| {
                        let best_dist = (*dist).min(distance);

                        distance = best_dist;
                        *dist = best_dist;
                    })
                    .or_insert(distance);

                if !visited.contains(&target) {
                    queue.push(QueueEntry {
                        node: target,
                        cur_cost: distance + heuristic(target),
                    })
                }
            }

            visited.insert(node);
        }

        None
    }

    /// Returns the shortest path from `from` to `to` using A*, together with its length.
    ///
    /// `heuristic` corresponds to the heuristic function of the A* algorithm.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use yagraphc::graph::UnGraph;
    /// use yagraphc::graph::traits::{GraphBuilding, Traversable};
    /// use yagraphc::graph::traits::ArithmeticallyWeightedGraph;
    ///
    /// let mut graph = UnGraph::new();
    ///
    /// graph.add_edge(1, 2, 1);
    /// graph.add_edge(2, 3, 2);
    /// graph.add_edge(3, 4, 3);
    /// graph.add_edge(1, 4, 7);
    ///
    /// assert_eq!(graph.a_star_with_path(1, 4, |_| 0).unwrap().0, vec![1, 2, 3, 4]);
    /// assert_eq!(graph.a_star_with_path(1, 5, |_| 0), None);
    fn a_star_with_path<G>(&self, from: T, to: T, heuristic: G) -> Option<(Vec<T>, W)>
    where
        Self: Traversable<T, W>,
        G: Fn(T) -> W,
    {
        let mut visited = HashSet::new();
        let mut distances = HashMap::new();

        distances.insert(from, (W::default(), from));

        let mut queue = BinaryHeap::new();
        queue.push(QueueEntry {
            node: from,
            cur_cost: W::default() + heuristic(from),
        });

        while let Some(QueueEntry { node, .. }) = queue.pop() {
            if visited.contains(&node) {
                continue;
            }

            if node == to {
                let mut path = Vec::new();

                let mut node = node;

                while node != from {
                    path.push(node);

                    node = distances[&node].1;
                }

                path.push(from);

                path.reverse();

                return Some((path, distances[&node].0));
            }

            for (target, weight) in self.edges(&node) {
                let mut distance = distances[&node].0 + weight;

                distances
                    .entry(target)
                    .and_modify(|(dist, prev)| {
                        if distance < *dist {
                            *dist = distance;
                            *prev = node;
                        } else {
                            distance = *dist
                        }
                    })
                    .or_insert((distance, node));

                if !visited.contains(&target) {
                    queue.push(QueueEntry {
                        node: target,
                        cur_cost: distance + heuristic(target),
                    })
                }
            }

            visited.insert(node);
        }

        None
    }

    /// Runs the Edmonds-Karp algorithm on the graph to find max flow.
    ///
    /// Assumes the edge weights are the capacities.
    ///
    /// Returns a HashMap with the flow values for each edge.
    ///
    /// Please select a number type for W which allows for subtraction
    /// and negative values, otherwise there may be undefined behavior.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use yagraphc::graph::UnGraph;
    /// use yagraphc::graph::traits::{ArithmeticallyWeightedGraph, GraphBuilding, Traversable};
    ///
    /// let mut graph = UnGraph::new();
    /// graph.add_edge(1, 2, 1000);
    /// graph.add_edge(2, 4, 1000);
    /// graph.add_edge(1, 3, 1000);
    /// graph.add_edge(3, 4, 1000);
    ///
    /// graph.add_edge(2, 3, 1);
    ///
    /// let flows = graph.edmonds_karp(1, 4);
    /// assert_eq!(*flows.get(&(1, 2)).unwrap(), 1000);
    /// assert_eq!(*flows.get(&(1, 3)).unwrap(), 1000);
    ///
    /// assert_eq!(*flows.get(&(2, 3)).unwrap_or(&0), 0);
    fn edmonds_karp(&self, source: T, sink: T) -> HashMap<(T, T), W>
    where
        Self: Traversable<T, W> + Sized,
    {
        let flows = HashMap::new();

        let mut residual_obtension = ResidualNetwork { flows, graph: self };

        while let Some(path) = self.find_path_filter_edges(source, sink, |x, y| {
            residual_obtension.get_residual_capacity(x, y) > W::default()
        }) {
            let residuals_in_path = path
                .iter()
                .zip(&path[1..])
                .map(|(&x, &y)| residual_obtension.get_residual_capacity(x, y));

            let min_res = residuals_in_path.min().expect("Path should not be empty");

            path.iter().zip(&path[1..]).for_each(|(&x, &y)| {
                residual_obtension
                    .flows
                    .entry((x, y))
                    .and_modify(|v| *v = *v + min_res)
                    .or_insert(min_res);
                residual_obtension
                    .flows
                    .entry((y, x))
                    .and_modify(|v| *v = *v - min_res)
                    .or_insert(W::default() - min_res);
            });

            residual_obtension = ResidualNetwork {
                flows: residual_obtension.flows,
                graph: self,
            };
        }

        residual_obtension.flows
    }
}

struct ResidualNetwork<'a, T, W> {
    flows: HashMap<(T, T), W>,
    graph: &'a dyn Traversable<T, W>,
}

impl<'a, T, W> ResidualNetwork<'a, T, W>
where
    T: Clone + Copy + Eq + Hash + PartialEq,
    W: Clone
        + Copy
        + std::ops::Add<Output = W>
        + std::ops::Sub<Output = W>
        + PartialOrd
        + Ord
        + Default,
{
    fn get_residual_capacity(&self, s: T, t: T) -> W {
        self.graph
            .edge_weight(s, t)
            .expect("Should only be considering existing edges")
            - self.flows.get(&(s, t)).copied().unwrap_or(W::default())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_error() {
        let e = NodeNotFound;
        dbg!(&e);
    }

    #[test]
    fn test_queue_entry() {
        let queue_entry1 = QueueEntry {
            node: 1,
            cur_cost: 12,
        };
        let queue_entry2 = QueueEntry {
            node: 4,
            cur_cost: 12,
        };

        assert!(queue_entry1 == queue_entry2);
    }
}