hello-algo/codes/swift/chapter_graph/graph_bfs.swift
Yudong Jin f68bbb0d59
Update the book based on the revised second edition (#1014)
* Revised the book

* Update the book with the second revised edition

* Revise base on the manuscript of the first edition
2023-12-28 18:06:09 +08:00

56 lines
1.8 KiB
Swift
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_bfs.swift
* Created Time: 2023-02-21
* Author: nuomi1 (nuomi1@qq.com)
*/
import graph_adjacency_list_target
import utils
/* 广 */
// 使便
func graphBFS(graph: GraphAdjList, startVet: Vertex) -> [Vertex] {
//
var res: [Vertex] = []
// 访
var visited: Set<Vertex> = [startVet]
// BFS
var que: [Vertex] = [startVet]
// vet 访
while !que.isEmpty {
let vet = que.removeFirst() //
res.append(vet) // 访
//
for adjVet in graph.adjList[vet] ?? [] {
if visited.contains(adjVet) {
continue // 访
}
que.append(adjVet) // 访
visited.insert(adjVet) // 访
}
}
//
return res
}
@main
enum GraphBFS {
/* Driver Code */
static func main() {
/* */
let v = Vertex.valsToVets(vals: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
let edges = [
[v[0], v[1]], [v[0], v[3]], [v[1], v[2]], [v[1], v[4]],
[v[2], v[5]], [v[3], v[4]], [v[3], v[6]], [v[4], v[5]],
[v[4], v[7]], [v[5], v[8]], [v[6], v[7]], [v[7], v[8]],
]
let graph = GraphAdjList(edges: edges)
print("\n初始化后,图为")
graph.print()
/* 广 */
let res = graphBFS(graph: graph, startVet: v[0])
print("\n广度优先遍历BFS顶点序列为")
print(Vertex.vetsToVals(vets: res))
}
}