@@ -233,14 +233,22 @@ func findSCC[K comparable](vertexHash K, state *sccState[K]) {
233233 }
234234}
235235
236- // AllPathsBetween list all paths from start to end.
236+ // AllPathsBetween computes and returns all paths between two given vertices. A
237+ // path is represented as a slice of vertex hashes. The returned slice contains
238+ // these paths.
239+ //
240+ // AllPathsBetween utilizes a non-recursive, stack-based implementation. It has
241+ // an estimated runtime complexity of O(n^2) where n is the number of vertices.
237242func AllPathsBetween [K comparable , T any ](g Graph [K , T ], start , end K ) ([][]K , error ) {
238243 adjacencyMap , err := g .AdjacencyMap ()
239244 if err != nil {
240245 return nil , err
241246 }
242247
243- mainStack , viceStack := newStack [K ](), newStack [stack [K ]]()
248+ // The algorithm used relies on stacks instead of recursion. It is described
249+ // here: https://boycgit.github.io/all-paths-between-two-vertex/
250+ mainStack := newStack [K ]()
251+ viceStack := newStack [stack [K ]]()
244252
245253 checkEmpty := func () error {
246254 if mainStack .isEmpty () || viceStack .isEmpty () {
@@ -270,10 +278,11 @@ func AllPathsBetween[K comparable, T any](g Graph[K, T], start, end K) ([][]K, e
270278
271279 buildStack := func () error {
272280 if err = checkEmpty (); err != nil {
273- return errors . New ( "empty stack" )
281+ return fmt . Errorf ( "unable to build stack: %w" , err )
274282 }
275283
276284 elements , _ := viceStack .top ()
285+
277286 for ! elements .isEmpty () {
278287 element , _ := elements .pop ()
279288 buildLayer (element )
@@ -285,11 +294,10 @@ func AllPathsBetween[K comparable, T any](g Graph[K, T], start, end K) ([][]K, e
285294
286295 removeLayer := func () error {
287296 if err = checkEmpty (); err != nil {
288- return errors . New ( "empty stack" )
297+ return fmt . Errorf ( "unable to remove layer: %w" , err )
289298 }
290299
291- e , _ := viceStack .top ()
292- if ! e .isEmpty () {
300+ if e , _ := viceStack .top (); ! e .isEmpty () {
293301 return errors .New ("the top element of vice-stack is not empty" )
294302 }
295303
@@ -299,12 +307,8 @@ func AllPathsBetween[K comparable, T any](g Graph[K, T], start, end K) ([][]K, e
299307 return nil
300308 }
301309
302- // init the first layer
303-
304310 buildLayer (start )
305311
306- // loop
307-
308312 allPaths := make ([][]K , 0 )
309313
310314 for ! mainStack .isEmpty () {
0 commit comments