This commit is contained in:
krahets
2024-04-09 20:43:40 +08:00
parent d8caf02e9e
commit a6adc8e20a
48 changed files with 1599 additions and 571 deletions

View File

@ -418,24 +418,24 @@ To prevent revisiting vertices, we use a hash table `visited` to record which no
```kotlin title="graph_bfs.kt"
/* 广度优先遍历 */
// 使用邻接表来表示图,以便获取指定顶点的所有邻接顶点
fun graphBFS(graph: GraphAdjList, startVet: Vertex): List<Vertex> {
fun graphBFS(graph: GraphAdjList, startVet: Vertex): MutableList<Vertex?> {
// 顶点遍历序列
val res: MutableList<Vertex> = ArrayList()
val res = mutableListOf<Vertex?>()
// 哈希表,用于记录已被访问过的顶点
val visited: MutableSet<Vertex> = HashSet()
val visited = HashSet<Vertex>()
visited.add(startVet)
// 队列用于实现 BFS
val que: Queue<Vertex> = LinkedList()
val que = LinkedList<Vertex>()
que.offer(startVet)
// 以顶点 vet 为起点,循环直至访问完所有顶点
while (!que.isEmpty()) {
val vet = que.poll() // 队首顶点出队
res.add(vet) // 记录访问顶点
res.add(vet) // 记录访问顶点
// 遍历该顶点的所有邻接顶点
for (adjVet in graph.adjList[vet]!!) {
if (visited.contains(adjVet)) continue // 跳过已被访问的顶点
que.offer(adjVet) // 只入队未访问的顶点
if (visited.contains(adjVet))
continue // 跳过已被访问的顶点
que.offer(adjVet) // 只入队未访问的顶点
visited.add(adjVet) // 标记该顶点已被访问
}
}
@ -866,11 +866,12 @@ This "go as far as possible and then return" algorithm paradigm is usually imple
res: MutableList<Vertex?>,
vet: Vertex?
) {
res.add(vet) // 记录访问顶点
res.add(vet) // 记录访问顶点
visited.add(vet) // 标记该顶点已被访问
// 遍历该顶点的所有邻接顶点
for (adjVet in graph.adjList[vet]!!) {
if (visited.contains(adjVet)) continue // 跳过已被访问的顶点
if (visited.contains(adjVet))
continue // 跳过已被访问的顶点
// 递归访问邻接顶点
dfs(graph, visited, res, adjVet)
}
@ -878,14 +879,11 @@ This "go as far as possible and then return" algorithm paradigm is usually imple
/* 深度优先遍历 */
// 使用邻接表来表示图,以便获取指定顶点的所有邻接顶点
fun graphDFS(
graph: GraphAdjList,
startVet: Vertex?
): List<Vertex?> {
fun graphDFS(graph: GraphAdjList, startVet: Vertex?): MutableList<Vertex?> {
// 顶点遍历序列
val res: MutableList<Vertex?> = ArrayList()
val res = mutableListOf<Vertex?>()
// 哈希表,用于记录已被访问过的顶点
val visited: MutableSet<Vertex?> = HashSet()
val visited = HashSet<Vertex?>()
dfs(graph, visited, res, startVet)
return res
}