Skip to content

Commit

Permalink
dfs
Browse files Browse the repository at this point in the history
  • Loading branch information
Yu Zhao committed May 19, 2018
1 parent 0a7395c commit 1f2208b
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions ch08/dfs.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package main

import (
"fmt"
"github.com/golang-collections/collections/stack"
)

type Node struct {
val int
links []*Node
}

func main() {
graph := &Node{1,[]*Node{
&Node{2, []*Node{
&Node{4,[]*Node{
&Node{5,[]*Node{}}}}}},
&Node{3,[]*Node{
&Node{6,[]*Node{}}}}}}
fmt.Println(DFS(graph, 5))
fmt.Println(DFS(graph, 7))
}

func DFS(node *Node, val int) bool {
stk := stack.New()

stk.Push(node)

for stk.Len() != 0 {
peek := stk.Peek().(*Node)
if peek.val == val {
return true
}
top := stk.Pop().(*Node)
for _, item := range top.links {
stk.Push(item)
}
}
return false
}

0 comments on commit 1f2208b

Please sign in to comment.