|
| 1 | + |
| 2 | +(* Stack-based DFS is tricky to get right. See |
| 3 | + https://11011110.github.io/blog/2013/12/17/stack-based-graph-traversal.html |
| 4 | +
|
| 5 | + On this graph, |
| 6 | +
|
| 7 | + 0 |
| 8 | + / \ |
| 9 | + / \ |
| 10 | + v v |
| 11 | + 1---2---3 (All edges are undirected, |
| 12 | + |\ /| apart from 0->1 0->3 1->5 and 3->6.) |
| 13 | + | \ / | |
| 14 | + | 4 | |
| 15 | + | / \ | |
| 16 | + v / \ v |
| 17 | + 5 6 |
| 18 | +
|
| 19 | + an incorrect stack-based DFS starting from 0 would first mark 1 and 3, |
| 20 | + and then would not go as deep as possible in the traversal. |
| 21 | +
|
| 22 | + In the following, we check that, whenever 2 and 4 are visited, |
| 23 | + then necessarily both 1 and 3 are already visited. |
| 24 | +*) |
| 25 | + |
| 26 | +open Format |
| 27 | +open Graph |
| 28 | +open Pack.Digraph |
| 29 | + |
| 30 | +let debug = false |
| 31 | + |
| 32 | +let g = create () |
| 33 | +let v = Array.init 7 V.create |
| 34 | +let () = Array.iter (add_vertex g) v |
| 35 | +let adde x y = add_edge g v.(x) v.(y) |
| 36 | +let addu x y = adde x y; adde y x |
| 37 | +let () = adde 0 1; adde 0 3 |
| 38 | +let () = addu 1 2; addu 2 3 |
| 39 | +let () = adde 1 5; adde 3 6 |
| 40 | +let () = addu 1 4; addu 4 3; addu 5 4; addu 4 6 |
| 41 | + |
| 42 | +let () = assert (Dfs.has_cycle g) |
| 43 | + |
| 44 | +let marked = Array.make 7 false |
| 45 | +let reset () = Array.fill marked 0 7 false |
| 46 | +let mark v = |
| 47 | + let i = V.label v in |
| 48 | + marked.(i) <- true; |
| 49 | + if marked.(2) && marked.(4) then assert (marked.(1) && marked.(3)) |
| 50 | + |
| 51 | +let pre v = if debug then printf "pre %d@." (V.label v); mark v |
| 52 | +let post v = if debug then printf "post %d@." (V.label v) |
| 53 | +let f v () = if debug then printf "fold %d@." (V.label v); mark v |
| 54 | + |
| 55 | +let () = reset (); Dfs.iter ~pre ~post g |
| 56 | +let () = reset (); Dfs.prefix pre g |
| 57 | +let () = reset (); Dfs.postfix post g |
| 58 | +let () = reset (); Dfs.iter_component ~pre ~post g v.(0) |
| 59 | +let () = reset (); Dfs.prefix_component pre g v.(0) |
| 60 | +let () = reset (); Dfs.postfix_component post g v.(0) |
| 61 | +let () = reset (); Dfs.fold f () g |
| 62 | +let () = reset (); Dfs.fold_component f () g v.(0) |
| 63 | + |
| 64 | +module D = Traverse.Dfs(Pack.Digraph) |
| 65 | + |
| 66 | +let rec visit it = |
| 67 | + let v = D.get it in |
| 68 | + mark v; |
| 69 | + visit (D.step it) |
| 70 | + |
| 71 | +let () = try visit (D.start g) with Exit -> () |
| 72 | + |
| 73 | +let () = printf "All tests succeeded.@." |
0 commit comments