From 12fcd54f8de16b8ccaa4f45bc0af24991a3363b2 Mon Sep 17 00:00:00 2001 From: Sergiu Ivanov Date: Mon, 11 Oct 2021 00:40:41 +0200 Subject: [PATCH] Add dfs. --- graph.rkt | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/graph.rkt b/graph.rkt index 5508fbe..c441966 100644 --- a/graph.rkt +++ b/graph.rkt @@ -33,6 +33,7 @@ matrix-graph? bfs fewest-vertices-path + dfs graphviz) @@ -117,6 +118,10 @@ (define (fewest-vertices-path G source target) (g:fewest-vertices-path (gg G) source target)) + ;; 4.2 Depth-first Search + (define (dfs g) + (g:dfs (gg g))) + ;; 10 Graphviz (define (graphviz g #:output [output #f] #:colors [colors #f]) (g:graphviz (gg g) #:output output #:colors colors))) @@ -170,6 +175,11 @@ (Mutable-HashTable Any Any)))] [fewest-vertices-path (-> Graph Any Any (U (Listof Any) False))] + ;; 4.2 Depth-first Search + [dfs (-> Graph (Values (Mutable-HashTable Any Number) + (Mutable-HashTable Any Any) + (Mutable-HashTable Any Number)))] + ;; 10 Graphviz [graphviz (->* (Graph) (#:output Output-Port @@ -251,7 +261,17 @@ (check-equal? (hash->ordered-list bfs-lens) '((a . 0) (b . 1) (c . 2))) (check-equal? (hash->ordered-list bfs-tree) '((a . #f) (b . a) (c . b))) (check-equal? (fewest-vertices-path (directed-graph '((a b) (b c) (c d))) 'a 'd) - '(a b c d))) + '(a b c d)) + + ;; 4.2 Depth-first Search + (define-values (dfs-discovery dfs-pred dfs-finish) + (dfs (directed-graph '((a b) (a c) (b d) (c d))))) + (check-equal? (hash->ordered-list dfs-discovery) + '((a . 4) (b . 5) (c . 0) (d . 1))) + (check-equal? (hash->ordered-list dfs-pred) + '((a . #f) (b . a) (c . #f) (d . c))) + (check-equal? (hash->ordered-list dfs-finish) + '((a . 7) (b . 6) (c . 3) (d . 2)))) (test-case "10 Graphviz" (define g (directed-graph '((a b) (b c))))