mirror of
https://github.com/krahets/hello-algo.git
synced 2024-12-24 10:46:29 +08:00
feat(go/graph): add go code for graph_dfs/bfs (#372)
* feat(vertex): add a vertex pkg * feat(graph): add graph_bfs in go * feat(graph): add graph_dfs in go * fix(graph): fix comment * fix(graph): fix graph_adj_list * fix(go/graph): fix graph_adjacency * fix(c): gitignore * feat(graph): print order adjList graph * fix(graph): remove order print * Update graph_adjacency_list_test.go * Update .gitignore * Update .gitignore --------- Co-authored-by: Yudong Jin <krahets@163.com>
This commit is contained in:
parent
9ea24e8b26
commit
327f385d32
8 changed files with 224 additions and 47 deletions
3
.gitignore
vendored
3
.gitignore
vendored
|
@ -3,7 +3,7 @@
|
||||||
|
|
||||||
# Editor
|
# Editor
|
||||||
.vscode/
|
.vscode/
|
||||||
.idea/
|
**/.idea
|
||||||
|
|
||||||
# mkdocs files
|
# mkdocs files
|
||||||
.cache/
|
.cache/
|
||||||
|
@ -13,3 +13,4 @@ docs/overrides/
|
||||||
build/
|
build/
|
||||||
site/
|
site/
|
||||||
utils/
|
utils/
|
||||||
|
**/cmake-build-debug
|
||||||
|
|
|
@ -8,31 +8,20 @@ import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
. "github.com/krahets/hello-algo/pkg"
|
||||||
)
|
)
|
||||||
|
|
||||||
/* 顶点类 */
|
|
||||||
type vertex struct {
|
|
||||||
val int
|
|
||||||
}
|
|
||||||
|
|
||||||
/* 构造方法 */
|
|
||||||
func newVertex(val int) vertex {
|
|
||||||
return vertex{
|
|
||||||
val: val,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/* 基于邻接表实现的无向图类 */
|
/* 基于邻接表实现的无向图类 */
|
||||||
type graphAdjList struct {
|
type graphAdjList struct {
|
||||||
// 邻接表,使用哈希表来代替链表,以提升删除边、删除顶点的效率
|
// 邻接表,key: 顶点,value:该顶点的所有邻接顶点
|
||||||
// 请注意,adjList 中的元素是 Vertex 对象
|
adjList map[Vertex][]Vertex
|
||||||
adjList map[vertex]map[vertex]struct{}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/* 构造方法 */
|
/* 构造方法 */
|
||||||
func newGraphAdjList(edges [][]vertex) *graphAdjList {
|
func newGraphAdjList(edges [][]Vertex) *graphAdjList {
|
||||||
g := &graphAdjList{
|
g := &graphAdjList{
|
||||||
adjList: make(map[vertex]map[vertex]struct{}),
|
adjList: make(map[Vertex][]Vertex),
|
||||||
}
|
}
|
||||||
// 添加所有顶点和边
|
// 添加所有顶点和边
|
||||||
for _, edge := range edges {
|
for _, edge := range edges {
|
||||||
|
@ -49,41 +38,41 @@ func (g *graphAdjList) size() int {
|
||||||
}
|
}
|
||||||
|
|
||||||
/* 添加边 */
|
/* 添加边 */
|
||||||
func (g *graphAdjList) addEdge(vet1 vertex, vet2 vertex) {
|
func (g *graphAdjList) addEdge(vet1 Vertex, vet2 Vertex) {
|
||||||
_, ok1 := g.adjList[vet1]
|
_, ok1 := g.adjList[vet1]
|
||||||
_, ok2 := g.adjList[vet2]
|
_, ok2 := g.adjList[vet2]
|
||||||
if !ok1 || !ok2 || vet1 == vet2 {
|
if !ok1 || !ok2 || vet1 == vet2 {
|
||||||
panic("error")
|
panic("error")
|
||||||
}
|
}
|
||||||
// 添加边 vet1 - vet2, 添加匿名 struct{},
|
// 添加边 vet1 - vet2, 添加匿名 struct{},
|
||||||
g.adjList[vet1][vet2] = struct{}{}
|
g.adjList[vet1] = append(g.adjList[vet1], vet2)
|
||||||
g.adjList[vet2][vet1] = struct{}{}
|
g.adjList[vet2] = append(g.adjList[vet2], vet1)
|
||||||
}
|
}
|
||||||
|
|
||||||
/* 删除边 */
|
/* 删除边 */
|
||||||
func (g *graphAdjList) removeEdge(vet1 vertex, vet2 vertex) {
|
func (g *graphAdjList) removeEdge(vet1 Vertex, vet2 Vertex) {
|
||||||
_, ok1 := g.adjList[vet1]
|
_, ok1 := g.adjList[vet1]
|
||||||
_, ok2 := g.adjList[vet2]
|
_, ok2 := g.adjList[vet2]
|
||||||
if !ok1 || !ok2 || vet1 == vet2 {
|
if !ok1 || !ok2 || vet1 == vet2 {
|
||||||
panic("error")
|
panic("error")
|
||||||
}
|
}
|
||||||
// 删除边 vet1 - vet2, 借助 delete 来删除 map 中的键
|
// 删除边 vet1 - vet2
|
||||||
delete(g.adjList[vet1], vet2)
|
DeleteSliceElms(g.adjList[vet1], vet2)
|
||||||
delete(g.adjList[vet2], vet1)
|
DeleteSliceElms(g.adjList[vet2], vet1)
|
||||||
}
|
}
|
||||||
|
|
||||||
/* 添加顶点 */
|
/* 添加顶点 */
|
||||||
func (g *graphAdjList) addVertex(vet vertex) {
|
func (g *graphAdjList) addVertex(vet Vertex) {
|
||||||
_, ok := g.adjList[vet]
|
_, ok := g.adjList[vet]
|
||||||
if ok {
|
if ok {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
// 在邻接表中添加一个新链表
|
// 在邻接表中添加一个新链表
|
||||||
g.adjList[vet] = make(map[vertex]struct{})
|
g.adjList[vet] = make([]Vertex, 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
/* 删除顶点 */
|
/* 删除顶点 */
|
||||||
func (g *graphAdjList) removeVertex(vet vertex) {
|
func (g *graphAdjList) removeVertex(vet Vertex) {
|
||||||
_, ok := g.adjList[vet]
|
_, ok := g.adjList[vet]
|
||||||
if !ok {
|
if !ok {
|
||||||
panic("error")
|
panic("error")
|
||||||
|
@ -91,9 +80,8 @@ func (g *graphAdjList) removeVertex(vet vertex) {
|
||||||
// 在邻接表中删除顶点 vet 对应的链表
|
// 在邻接表中删除顶点 vet 对应的链表
|
||||||
delete(g.adjList, vet)
|
delete(g.adjList, vet)
|
||||||
// 遍历其它顶点的链表,删除所有包含 vet 的边
|
// 遍历其它顶点的链表,删除所有包含 vet 的边
|
||||||
for _, set := range g.adjList {
|
for _, list := range g.adjList {
|
||||||
// 操作
|
DeleteSliceElms(list, vet)
|
||||||
delete(set, vet)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -101,10 +89,11 @@ func (g *graphAdjList) removeVertex(vet vertex) {
|
||||||
func (g *graphAdjList) print() {
|
func (g *graphAdjList) print() {
|
||||||
var builder strings.Builder
|
var builder strings.Builder
|
||||||
fmt.Printf("邻接表 = \n")
|
fmt.Printf("邻接表 = \n")
|
||||||
|
// 使邻接表有序输出
|
||||||
for k, v := range g.adjList {
|
for k, v := range g.adjList {
|
||||||
builder.WriteString("\t\t" + strconv.Itoa(k.val) + ": ")
|
builder.WriteString("\t\t" + strconv.Itoa(k.Val) + ": ")
|
||||||
for vet := range v {
|
for _, vet := range v {
|
||||||
builder.WriteString(strconv.Itoa(vet.val) + " ")
|
builder.WriteString(strconv.Itoa(vet.Val) + " ")
|
||||||
}
|
}
|
||||||
fmt.Println(builder.String())
|
fmt.Println(builder.String())
|
||||||
builder.Reset()
|
builder.Reset()
|
||||||
|
|
|
@ -7,41 +7,39 @@ package chapter_graph
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
. "github.com/krahets/hello-algo/pkg"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestGraphAdjList(t *testing.T) {
|
func TestGraphAdjList(t *testing.T) {
|
||||||
/* 初始化无向图 */
|
/* 初始化无向图 */
|
||||||
v0 := newVertex(1)
|
v := ValsToVets([]int{1, 3, 2, 5, 4})
|
||||||
v1 := newVertex(3)
|
edges := [][]Vertex{{v[0], v[1]}, {v[0], v[3]}, {v[1], v[2]}, {v[2], v[3]}, {v[2], v[4]}, {v[3], v[4]}}
|
||||||
v2 := newVertex(2)
|
|
||||||
v3 := newVertex(5)
|
|
||||||
v4 := newVertex(4)
|
|
||||||
edges := [][]vertex{{v0, v1}, {v1, v2}, {v2, v3}, {v0, v3}, {v2, v4}, {v3, v4}}
|
|
||||||
graph := newGraphAdjList(edges)
|
graph := newGraphAdjList(edges)
|
||||||
fmt.Println("初始化后,图为:")
|
fmt.Println("初始化后,图为:")
|
||||||
graph.print()
|
graph.print()
|
||||||
|
|
||||||
/* 添加边 */
|
/* 添加边 */
|
||||||
// 顶点 1, 2 即 v0, v2
|
// 顶点 1, 2 即 v[0], v[2]
|
||||||
graph.addEdge(v0, v2)
|
graph.addEdge(v[0], v[2])
|
||||||
fmt.Println("\n添加边 1-2 后,图为")
|
fmt.Println("\n添加边 1-2 后,图为")
|
||||||
graph.print()
|
graph.print()
|
||||||
|
|
||||||
/* 删除边 */
|
/* 删除边 */
|
||||||
// 顶点 1, 3 即 v0, v1
|
// 顶点 1, 3 即 v[0], v[1]
|
||||||
graph.removeEdge(v0, v1)
|
graph.removeEdge(v[0], v[1])
|
||||||
fmt.Println("\n删除边 1-3 后,图为")
|
fmt.Println("\n删除边 1-3 后,图为")
|
||||||
graph.print()
|
graph.print()
|
||||||
|
|
||||||
/* 添加顶点 */
|
/* 添加顶点 */
|
||||||
v5 := newVertex(6)
|
v5 := NewVertex(6)
|
||||||
graph.addVertex(v5)
|
graph.addVertex(v5)
|
||||||
fmt.Println("\n添加顶点 6 后,图为")
|
fmt.Println("\n添加顶点 6 后,图为")
|
||||||
graph.print()
|
graph.print()
|
||||||
|
|
||||||
/* 删除顶点 */
|
/* 删除顶点 */
|
||||||
// 顶点 3 即 v1
|
// 顶点 3 即 v[1]
|
||||||
graph.removeVertex(v1)
|
graph.removeVertex(v[1])
|
||||||
fmt.Println("\n删除顶点 3 后,图为")
|
fmt.Println("\n删除顶点 3 后,图为")
|
||||||
graph.print()
|
graph.print()
|
||||||
}
|
}
|
||||||
|
|
41
codes/go/chapter_graph/graph_bfs.go
Normal file
41
codes/go/chapter_graph/graph_bfs.go
Normal file
|
@ -0,0 +1,41 @@
|
||||||
|
// File: graph_bfs.go
|
||||||
|
// Created Time: 2023-02-18
|
||||||
|
// Author: Reanon (793584285@qq.com)
|
||||||
|
|
||||||
|
package chapter_graph
|
||||||
|
|
||||||
|
import (
|
||||||
|
. "github.com/krahets/hello-algo/pkg"
|
||||||
|
)
|
||||||
|
|
||||||
|
/* 广度优先遍历 BFS */
|
||||||
|
// 使用邻接表来表示图,以便获取指定顶点的所有邻接顶点
|
||||||
|
func graphBFS(g *graphAdjList, startVet Vertex) []Vertex {
|
||||||
|
// 顶点遍历序列
|
||||||
|
res := make([]Vertex, 0)
|
||||||
|
// 哈希表,用于记录已被访问过的顶点
|
||||||
|
visited := make(map[Vertex]struct{})
|
||||||
|
visited[startVet] = struct{}{}
|
||||||
|
// 队列用于实现 BFS, 使用切片模拟队列
|
||||||
|
queue := make([]Vertex, 0)
|
||||||
|
queue = append(queue, startVet)
|
||||||
|
// 以顶点 vet 为起点,循环直至访问完所有顶点
|
||||||
|
for len(queue) > 0 {
|
||||||
|
// 队首顶点出队
|
||||||
|
vet := queue[0]
|
||||||
|
queue = queue[1:]
|
||||||
|
// 记录访问顶点
|
||||||
|
res = append(res, vet)
|
||||||
|
// 遍历该顶点的所有邻接顶点
|
||||||
|
for _, adjVet := range g.adjList[vet] {
|
||||||
|
_, isExist := visited[adjVet]
|
||||||
|
// 只入队未访问的顶点
|
||||||
|
if !isExist {
|
||||||
|
queue = append(queue, adjVet)
|
||||||
|
visited[adjVet] = struct{}{}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 返回顶点遍历序列
|
||||||
|
return res
|
||||||
|
}
|
29
codes/go/chapter_graph/graph_bfs_test.go
Normal file
29
codes/go/chapter_graph/graph_bfs_test.go
Normal file
|
@ -0,0 +1,29 @@
|
||||||
|
// File: graph_bfs_test.go
|
||||||
|
// Created Time: 2023-02-18
|
||||||
|
// Author: Reanon (793584285@qq.com)
|
||||||
|
|
||||||
|
package chapter_graph
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
. "github.com/krahets/hello-algo/pkg"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestGraphBFS(t *testing.T) {
|
||||||
|
/* 初始化无向图 */
|
||||||
|
vets := ValsToVets([]int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9})
|
||||||
|
edges := [][]Vertex{
|
||||||
|
{vets[0], vets[1]}, {vets[0], vets[3]}, {vets[1], vets[2]}, {vets[1], vets[4]},
|
||||||
|
{vets[2], vets[5]}, {vets[3], vets[4]}, {vets[3], vets[6]}, {vets[4], vets[5]},
|
||||||
|
{vets[4], vets[7]}, {vets[5], vets[8]}, {vets[6], vets[7]}, {vets[7], vets[8]}}
|
||||||
|
graph := newGraphAdjList(edges)
|
||||||
|
fmt.Println("初始化后,图为:")
|
||||||
|
graph.print()
|
||||||
|
|
||||||
|
/* 广度优先遍历 BFS */
|
||||||
|
res := graphBFS(graph, vets[0])
|
||||||
|
fmt.Println("广度优先遍历(BFS)顶点序列为:")
|
||||||
|
PrintSlice(VetsToVals(res))
|
||||||
|
}
|
36
codes/go/chapter_graph/graph_dfs.go
Normal file
36
codes/go/chapter_graph/graph_dfs.go
Normal file
|
@ -0,0 +1,36 @@
|
||||||
|
// File: graph_dfs.go
|
||||||
|
// Created Time: 2023-02-18
|
||||||
|
// Author: Reanon (793584285@qq.com)
|
||||||
|
|
||||||
|
package chapter_graph
|
||||||
|
|
||||||
|
import (
|
||||||
|
. "github.com/krahets/hello-algo/pkg"
|
||||||
|
)
|
||||||
|
|
||||||
|
/* 深度优先遍历 DFS 辅助函数 */
|
||||||
|
func dfs(g *graphAdjList, visited map[Vertex]struct{}, res *[]Vertex, vet Vertex) {
|
||||||
|
// append 操作会返回新的的引用,必须让原引用重新赋值为新slice的引用
|
||||||
|
*res = append(*res, vet)
|
||||||
|
visited[vet] = struct{}{}
|
||||||
|
// 遍历该顶点的所有邻接顶点
|
||||||
|
for _, adjVet := range g.adjList[vet] {
|
||||||
|
_, isExist := visited[adjVet]
|
||||||
|
// 递归访问邻接顶点
|
||||||
|
if !isExist {
|
||||||
|
dfs(g, visited, res, adjVet)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 深度优先遍历 DFS */
|
||||||
|
// 使用邻接表来表示图,以便获取指定顶点的所有邻接顶点
|
||||||
|
func graphDFS(g *graphAdjList, startVet Vertex) []Vertex {
|
||||||
|
// 顶点遍历序列
|
||||||
|
res := make([]Vertex, 0)
|
||||||
|
// 哈希表,用于记录已被访问过的顶点
|
||||||
|
visited := make(map[Vertex]struct{})
|
||||||
|
dfs(g, visited, &res, startVet)
|
||||||
|
// 返回顶点遍历序列
|
||||||
|
return res
|
||||||
|
}
|
28
codes/go/chapter_graph/graph_dfs_test.go
Normal file
28
codes/go/chapter_graph/graph_dfs_test.go
Normal file
|
@ -0,0 +1,28 @@
|
||||||
|
// File: graph_dfs_test.go
|
||||||
|
// Created Time: 2023-02-18
|
||||||
|
// Author: Reanon (793584285@qq.com)
|
||||||
|
|
||||||
|
package chapter_graph
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
. "github.com/krahets/hello-algo/pkg"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestGraphDFS(t *testing.T) {
|
||||||
|
/* 初始化无向图 */
|
||||||
|
vets := ValsToVets([]int{0, 1, 2, 3, 4, 5, 6})
|
||||||
|
edges := [][]Vertex{
|
||||||
|
{vets[0], vets[1]}, {vets[0], vets[3]}, {vets[1], vets[2]},
|
||||||
|
{vets[2], vets[5]}, {vets[4], vets[5]}, {vets[5], vets[6]}}
|
||||||
|
graph := newGraphAdjList(edges)
|
||||||
|
fmt.Println("初始化后,图为:")
|
||||||
|
graph.print()
|
||||||
|
|
||||||
|
/* 深度优先遍历 DFS */
|
||||||
|
res := graphDFS(graph, vets[0])
|
||||||
|
fmt.Println("深度优先遍历(DFS)顶点序列为:")
|
||||||
|
PrintSlice(VetsToVals(res))
|
||||||
|
}
|
55
codes/go/pkg/vertex.go
Normal file
55
codes/go/pkg/vertex.go
Normal file
|
@ -0,0 +1,55 @@
|
||||||
|
// File: vertex.go
|
||||||
|
// Created Time: 2023-02-18
|
||||||
|
// Author: Reanon (793584285@qq.com)
|
||||||
|
|
||||||
|
package pkg
|
||||||
|
|
||||||
|
// Vertex 顶点类
|
||||||
|
type Vertex struct {
|
||||||
|
Val int
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewVertex 构造方法
|
||||||
|
func NewVertex(val int) Vertex {
|
||||||
|
return Vertex{
|
||||||
|
Val: val,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ValsToVets Generate a vertex list tree given an array
|
||||||
|
func ValsToVets(vals []int) []Vertex {
|
||||||
|
vets := make([]Vertex, len(vals))
|
||||||
|
for i := 0; i < len(vals); i++ {
|
||||||
|
vets[i] = NewVertex(vals[i])
|
||||||
|
}
|
||||||
|
return vets
|
||||||
|
}
|
||||||
|
|
||||||
|
// VetsToVals Serialize given vertex list to a value list
|
||||||
|
func VetsToVals(vets []Vertex) []int {
|
||||||
|
vals := make([]int, len(vets))
|
||||||
|
for i := range vets {
|
||||||
|
vals[i] = vets[i].Val
|
||||||
|
}
|
||||||
|
return vals
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteSliceElms 删除切片指定元素
|
||||||
|
func DeleteSliceElms[T any](a []T, elms ...T) []T {
|
||||||
|
if len(a) == 0 || len(elms) == 0 {
|
||||||
|
return a
|
||||||
|
}
|
||||||
|
// 先将元素转为 set
|
||||||
|
m := make(map[any]struct{})
|
||||||
|
for _, v := range elms {
|
||||||
|
m[v] = struct{}{}
|
||||||
|
}
|
||||||
|
// 过滤掉指定元素
|
||||||
|
res := make([]T, 0, len(a))
|
||||||
|
for _, v := range a {
|
||||||
|
if _, ok := m[v]; !ok {
|
||||||
|
res = append(res, v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return res
|
||||||
|
}
|
Loading…
Reference in a new issue