hello-algo/zh-hant/codes/swift/chapter_graph/graph_bfs.swift

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