Skip to content

Instantly share code, notes, and snippets.

@kiambogo
Last active May 10, 2021 06:45
Show Gist options
  • Save kiambogo/336deb0e58e17c800413dfec0335fe2b to your computer and use it in GitHub Desktop.
Save kiambogo/336deb0e58e17c800413dfec0335fe2b to your computer and use it in GitHub Desktop.
Go DFS
package main
import "log"
type Node struct {
val int
marked bool
children []*Node
}
type Graph struct {
root *Node
}
func main() {
graph := makeGraph()
dfs(graph[0])
}
func dfs(node *Node) {
if node == nil {
return
}
visit(node)
for _, child := range node.children {
child := child
if !child.marked {
child.marked = true
dfs(child)
}
}
}
func visit(n *Node) {
log.Println(n.val)
}
func makeGraph() []*Node {
zero := &Node{val: 0}
one := &Node{val: 1}
two := &Node{val: 2}
three := &Node{val: 3}
four := &Node{val: 4}
five := &Node{val: 5}
zero.children = []*Node{one, four, five}
one.children = []*Node{three, four}
two.children = []*Node{one}
three.children = []*Node{two, four}
return []*Node{zero, one, two, three, four, five}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment