hello-algo/zh-hant/codes/go/chapter_graph/graph_dfs.go
Yudong Jin 870e3e5cb2
Bug fixes and improvements (#1318)
* Sync zh and zh-hant versions

* Update en/README.md

* Add a Q&A for chapter of introduction

* Update the callout headers

* Sync zh ang zh-hant versions

* Bug fixes
2024-04-30 15:52:05 +08:00

36 lines
1,015 B
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// File: graph_dfs.go
// Created Time: 2023-02-18
// Author: Reanon (793584285@qq.com)
package chapter_graph
import (
. "github.com/krahets/hello-algo/pkg"
)
/* 深度優先走訪輔助函式 */
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)
}
}
}
/* 深度優先走訪 */
// 使用鄰接表來表示圖,以便獲取指定頂點的所有鄰接頂點
func graphDFS(g *graphAdjList, startVet Vertex) []Vertex {
// 頂點走訪序列
res := make([]Vertex, 0)
// 雜湊集合,用於記錄已被訪問過的頂點
visited := make(map[Vertex]struct{})
dfs(g, visited, &res, startVet)
// 返回頂點走訪序列
return res
}