-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraph.go
More file actions
64 lines (48 loc) · 978 Bytes
/
graph.go
File metadata and controls
64 lines (48 loc) · 978 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package GoGraph
func NewNode(value string, edges []*Node) *Node {
n := Node{
Edges: edges,
Value: value,
}
return &n
}
type Node struct {
Edges []*Node
Value string
}
func DepthFirstSearch(from *Node, to string) bool {
visited := make(map[string]bool)
return dfs(from, to, visited)
}
func dfs(current *Node, target string, visited map[string]bool) bool {
if current.Value == target {
return true
}
if visited[current.Value] {
return false
}
visited[current.Value] = true
for _, edge := range current.Edges {
if dfs(edge, target, visited) {
return true
}
}
return false
}
func BreadthFirstSearch(from *Node, to string) bool {
visited := make(map[string]bool)
queue := []*Node{from}
for len(queue) > 0 {
current := queue[0]
queue = queue[1:]
if visited[current.Value] {
continue
}
visited[current.Value] = true
if current.Value == to {
return true
}
queue = append(queue, current.Edges...)
}
return false
}