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:
Reanon 2023-02-27 20:34:30 +08:00 committed by GitHub
parent 9ea24e8b26
commit 327f385d32
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
8 changed files with 224 additions and 47 deletions

3
.gitignore vendored
View file

@ -3,7 +3,7 @@
# Editor
.vscode/
.idea/
**/.idea
# mkdocs files
.cache/
@ -13,3 +13,4 @@ docs/overrides/
build/
site/
utils/
**/cmake-build-debug

View file

@ -8,31 +8,20 @@ import (
"fmt"
"strconv"
"strings"
. "github.com/krahets/hello-algo/pkg"
)
/* 顶点类 */
type vertex struct {
val int
}
/* 构造方法 */
func newVertex(val int) vertex {
return vertex{
val: val,
}
}
/* 基于邻接表实现的无向图类 */
type graphAdjList struct {
// 邻接表,使用哈希表来代替链表,以提升删除边、删除顶点的效率
// 请注意adjList 中的元素是 Vertex 对象
adjList map[vertex]map[vertex]struct{}
// 邻接表key: 顶点value该顶点的所有邻接顶点
adjList map[Vertex][]Vertex
}
/* 构造方法 */
func newGraphAdjList(edges [][]vertex) *graphAdjList {
func newGraphAdjList(edges [][]Vertex) *graphAdjList {
g := &graphAdjList{
adjList: make(map[vertex]map[vertex]struct{}),
adjList: make(map[Vertex][]Vertex),
}
// 添加所有顶点和边
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]
_, ok2 := g.adjList[vet2]
if !ok1 || !ok2 || vet1 == vet2 {
panic("error")
}
// 添加边 vet1 - vet2, 添加匿名 struct{},
g.adjList[vet1][vet2] = struct{}{}
g.adjList[vet2][vet1] = struct{}{}
g.adjList[vet1] = append(g.adjList[vet1], vet2)
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]
_, ok2 := g.adjList[vet2]
if !ok1 || !ok2 || vet1 == vet2 {
panic("error")
}
// 删除边 vet1 - vet2, 借助 delete 来删除 map 中的键
delete(g.adjList[vet1], vet2)
delete(g.adjList[vet2], vet1)
// 删除边 vet1 - vet2
DeleteSliceElms(g.adjList[vet1], vet2)
DeleteSliceElms(g.adjList[vet2], vet1)
}
/* 添加顶点 */
func (g *graphAdjList) addVertex(vet vertex) {
func (g *graphAdjList) addVertex(vet Vertex) {
_, ok := g.adjList[vet]
if ok {
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]
if !ok {
panic("error")
@ -91,9 +80,8 @@ func (g *graphAdjList) removeVertex(vet vertex) {
// 在邻接表中删除顶点 vet 对应的链表
delete(g.adjList, vet)
// 遍历其它顶点的链表,删除所有包含 vet 的边
for _, set := range g.adjList {
// 操作
delete(set, vet)
for _, list := range g.adjList {
DeleteSliceElms(list, vet)
}
}
@ -101,10 +89,11 @@ func (g *graphAdjList) removeVertex(vet vertex) {
func (g *graphAdjList) print() {
var builder strings.Builder
fmt.Printf("邻接表 = \n")
// 使邻接表有序输出
for k, v := range g.adjList {
builder.WriteString("\t\t" + strconv.Itoa(k.val) + ": ")
for vet := range v {
builder.WriteString(strconv.Itoa(vet.val) + " ")
builder.WriteString("\t\t" + strconv.Itoa(k.Val) + ": ")
for _, vet := range v {
builder.WriteString(strconv.Itoa(vet.Val) + " ")
}
fmt.Println(builder.String())
builder.Reset()

View file

@ -7,41 +7,39 @@ package chapter_graph
import (
"fmt"
"testing"
. "github.com/krahets/hello-algo/pkg"
)
func TestGraphAdjList(t *testing.T) {
/* 初始化无向图 */
v0 := newVertex(1)
v1 := newVertex(3)
v2 := newVertex(2)
v3 := newVertex(5)
v4 := newVertex(4)
edges := [][]vertex{{v0, v1}, {v1, v2}, {v2, v3}, {v0, v3}, {v2, v4}, {v3, v4}}
v := ValsToVets([]int{1, 3, 2, 5, 4})
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]}}
graph := newGraphAdjList(edges)
fmt.Println("初始化后,图为:")
graph.print()
/* 添加边 */
// 顶点 1, 2 即 v0, v2
graph.addEdge(v0, v2)
// 顶点 1, 2 即 v[0], v[2]
graph.addEdge(v[0], v[2])
fmt.Println("\n添加边 1-2 后,图为")
graph.print()
/* 删除边 */
// 顶点 1, 3 即 v0, v1
graph.removeEdge(v0, v1)
// 顶点 1, 3 即 v[0], v[1]
graph.removeEdge(v[0], v[1])
fmt.Println("\n删除边 1-3 后,图为")
graph.print()
/* 添加顶点 */
v5 := newVertex(6)
v5 := NewVertex(6)
graph.addVertex(v5)
fmt.Println("\n添加顶点 6 后,图为")
graph.print()
/* 删除顶点 */
// 顶点 3 即 v1
graph.removeVertex(v1)
// 顶点 3 即 v[1]
graph.removeVertex(v[1])
fmt.Println("\n删除顶点 3 后,图为")
graph.print()
}

View 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
}

View 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))
}

View 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
}

View 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
View 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
}