Debian Codegraph @

example_dfs_test.go

raw symbols SCIP
1 package graph_test
2
3 import (
4 "fmt"
5 "github.com/yourbasic/graph"
6 )
7
8 const (
9 White = iota
10 Gray
11 Black
12 )
13
14 // The package doesn't support vertex labeling. However,
15 // since vertices are always numbered 0..n-1, it's easy
16 // to add this type of data on the side. This implementation
17 // of depth-first search uses separate slices to keep track of
18 // vertex colors, predecessors and discovery times.
19 type DFSData struct {
20 Time int
21 Color []int
22 Prev []int
23 Discover []int
24 Finish []int
25 }
26
27 func DFS(g graph.Iterator) DFSData {
28 n := g.Order() // Order returns the number of vertices.
29 d := DFSData{
30 Time: 0,
31 Color: make([]int, n),
32 Prev: make([]int, n),
33 Discover: make([]int, n),
34 Finish: make([]int, n),
35 }
36 for v := 0; v < n; v++ {
37 d.Color[v] = White
38 d.Prev[v] = -1
39 }
40 for v := 0; v < n; v++ {
41 if d.Color[v] == White {
42 d.dfsVisit(g, v)
43 }
44 }
45 return d
46 }
47
48 func (d *DFSData) dfsVisit(g graph.Iterator, v int) {
49 d.Color[v] = Gray
50 d.Time++
51 d.Discover[v] = d.Time
52 // Visit calls a function for each neighbor w of v,
53 // with c equal to the cost of the edge (v, w).
54 // The iteration is aborted if the function returns true.
55 g.Visit(v, func(w int, c int64) (skip bool) {
56 if d.Color[w] == White {
57 d.Prev[w] = v
58 d.dfsVisit(g, w)
59 }
60 return
61 })
62 d.Color[v] = Black
63 d.Time++
64 d.Finish[v] = d.Time
65 }
66
67 // Show how to use this package by implementing a complete depth-first search.
68 func Example_dFS() {
69 // Build a small directed graph:
70 //
71 // 0 ---> 1 <--> 2 3
72 //
73 g := graph.New(4)
74 g.Add(0, 1)
75 g.AddBoth(1, 2)
76
77 fmt.Println(g)
78 fmt.Println(DFS(g))
79 // Output:
80 // 4 [(0 1) {1 2}]
81 // {8 [2 2 2 2] [-1 0 1 -1] [1 2 3 7] [6 5 4 8]}
82 }