You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
hello-algo/codes/swift/chapter_graph/graph_bfs.swift

57 lines
1.8 KiB

/**
* File: graph_bfs.swift
* Created Time: 2023-02-21
* Author: nuomi1 (nuomi1@qq.com)
*/
import graph_adjacency_list_target
import utils
/* 广 BFS */
// 使便
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()
/* 广 BFS */
let res = graphBFS(graph: graph, startVet: v[0])
print("\n广度优先遍历BFS顶点序列为")
print(Vertex.vetsToVals(vets: res))
}
}