-
Notifications
You must be signed in to change notification settings - Fork 133
/
Copy pathiterative_traversal.go
64 lines (56 loc) · 1.7 KB
/
iterative_traversal.go
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 graph
type (
// Vertex is a vertex in a Graph that has a value and can be connected to more vertices.
Vertex struct {
// Val is the value of the vertex
Val int
// The edges that this Vertex is connected to
Edges []*Vertex
}
queue struct{ collection []*Vertex }
stack struct{ collection []*Vertex }
container interface {
Push(n *Vertex)
Pop() *Vertex
Len() int
}
)
// IterativeTraversal solves the problem in O(n) time and O(n) space.
func IterativeTraversal(graph []*Vertex) ([]int, []int) {
dfs := traverseAllNodes(new(stack), graph)
bfs := traverseAllNodes(new(queue), graph)
return bfs, dfs
}
// traverseAllNodes performs BFS or DFS if a graph and a container that is
// either respectively a stack or queue passed to it.
func traverseAllNodes(c container, graph []*Vertex) []int {
output := []int{}
visited := make(map[*Vertex]struct{})
c.Push(graph[0])
for c.Len() != 0 {
tmp := c.Pop()
for _, neighbor := range tmp.Edges {
c.Push(neighbor)
}
if _, ok := visited[tmp]; !ok {
output = append(output, tmp.Val)
visited[tmp] = struct{}{}
}
}
return output
}
func newVertex(v int) *Vertex { return &Vertex{Val: v, Edges: []*Vertex{}} }
func (q *queue) Len() int { return len(q.collection) }
func (q *queue) Push(n *Vertex) { q.collection = append(q.collection, n) }
func (q *queue) Pop() *Vertex {
tmp := q.collection[0]
q.collection = q.collection[1:len(q.collection)]
return tmp
}
func (s *stack) Len() int { return len(s.collection) }
func (s *stack) Push(n *Vertex) { s.collection = append(s.collection, n) }
func (s *stack) Pop() *Vertex {
tmp := s.collection[len(s.collection)-1]
s.collection = s.collection[:len(s.collection)-1]
return tmp
}