0 | module Data.Graph.Indexed.Query.BFS
3 | import Data.Graph.Indexed
4 | import Data.Graph.Indexed.Query.Util
5 | import Data.Graph.Indexed.Query.Visited
12 | -> (s -> Fin k -> Either s a)
15 | -> Either (Queue (s, Fin k)) a
16 | enqueueE q f st [] = Left q
17 | enqueueE q f st (x::xs) =
20 | Left st2 => enqueueE (enqueue q (st2, x)) f st xs
22 | parameters {k : Nat}
30 | bfsL : Queue (s,Fin k) -> (s -> Fin k -> Either s a) -> MVis t k (Maybe a)
33 | Nothing => Nothing # t
35 | let False # t := mvisited r x t
36 | | True # t => bfsL q2 f (assert_smaller r r) t
37 | Left q3 := enqueueE q2 f vs (neighbours g x) | Right v => Just v # t
38 | _ # t := mvisit r x t
39 | in bfsL q3 f (assert_smaller r r) t
53 | (taboo : List (Fin k))
54 | -> (s -> Fin k -> Either s a)
58 | limitedBfsWith taboo acc init x =
59 | visiting k $
\r,t =>
60 | let _ # t := mvisitAll r taboo t
61 | in bfsL (fromList [(init,x)]) acc r t
67 | bfsWith : (s -> Fin k -> Either s a) -> (init : s) -> Fin k -> Maybe a
68 | bfsWith = limitedBfsWith []
73 | (taboo : List (Fin k))
76 | -> Maybe (SnocList (Fin k))
77 | limitedBfs taboo start end =
78 | if start == end then Just [< start]
82 | (\sx,x => if x == end then Right (sx :< x) else Left (sx :< x))
88 | bfs : Fin k -> Fin k -> Maybe (SnocList (Fin k))
96 | bfsAllL : SnocList s -> Queue (s,Fin k) -> (s -> Fin k -> s) -> MVis t k (List s)
97 | bfsAllL ss q f r t =
99 | Nothing => (ss <>> []) # t
100 | Just ((vs,x),q2) =>
101 | let False # t := mvisited r x t
102 | | True # t => bfsAllL ss q2 f (assert_smaller r r) t
103 | q3 := enqueueAll q2 (map (\y => (f vs y, y)) $
neighbours g x)
104 | _ # t := mvisit r x t
105 | in bfsAllL (ss :< vs) q3 f (assert_smaller r r) t
111 | bfsAllWith : (s -> Fin k -> s) -> (init : s) -> Fin k -> List s
112 | bfsAllWith acc init x =
113 | visiting k (bfsAllL [<] (fromList [(init,x)]) acc)
116 | distancesToNode : Fin k -> List (Nat, Fin k)
117 | distancesToNode x = bfsAllWith (\x,y => (S $
fst x, y)) (0,x) x
125 | SnocList (SnocList $
Fin k)
126 | -> Queue (SnocList $
Fin k)
127 | -> MVis t k (List (SnocList $
Fin k))
128 | shortestL sp q r t =
130 | Nothing => (sp <>> []) # t
131 | Just (sx@(_:<x),q2) =>
132 | let False # t := mvisited r x t | True # t => shortestL sp q2 r t
133 | ns := map (sx :<) (neighbours g x)
134 | _ # t := mvisit r x t
135 | in shortestL (sp :< sx) (enqueueAll q2 ns) r t
136 | Just (_,q2) => shortestL sp q2 r t
144 | shortestPaths : Fin k -> List (SnocList $
Fin k)
146 | let q := fromList $
map ([<x] :<) (neighbours g x)
148 | visiting k $
\r,t => let _ # t := mvisit r x t in shortestL [<] q r t