- Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathdfs.go
48 lines (42 loc) · 1.13 KB
/
dfs.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
package dfs
import (
"github.com/xiaomeng79/go-algorithm/data-structures/graph"
"github.com/xiaomeng79/go-algorithm/data-structures/stack"
)
//无向图的深度搜索
funcUndirectedDfs(g*graph.UnGraph, v graph.VertexId, fnfunc(graph.VertexId)) {
s:=stack.New() //初始化一个栈
s.Push(int(v))
visited:=make(map[graph.VertexId]bool) //记录是否访问过
fors.Len() >0 { //只要栈里面有,就一直
v, _:=s.Pop()
_v:=graph.VertexId(v)
if_, ok:=visited[_v]; !ok {
visited[_v] =true
fn(_v)
//将此结点的邻接点压栈
neighbours:=g.GetNeighbours(_v).VerticesIter()
forneighbour:=rangeneighbours {
s.Push(int(neighbour))
}
}
}
}
//有向图的深度搜索
funcDirectedDfs(g*graph.DirGraph, v graph.VertexId, fnfunc(graph.VertexId)) {
s:=stack.New()
s.Push(int(v))
visited:=make(map[graph.VertexId]bool)
fors.Len() >0 {
v, _:=s.Pop()
_v:=graph.VertexId(v)
if_, ok:=visited[_v]; !ok {
visited[_v] =true
fn(_v)
neighbours:=g.GetSuccessors(_v).VerticesIter()
forneighbour:=rangeneighbours {
s.Push(int(neighbour))
}
}
}
}