hello-algo/codes/swift/chapter_graph/graph_bfs.swift
Yudong Jin e720aa2d24
feat: Revised the book (#978)
* Sync recent changes to the revised Word.

* Revised the preface chapter

* Revised the introduction chapter

* Revised the computation complexity chapter

* Revised the chapter data structure

* Revised the chapter array and linked list

* Revised the chapter stack and queue

* Revised the chapter hashing

* Revised the chapter tree

* Revised the chapter heap

* Revised the chapter graph

* Revised the chapter searching

* Reivised the sorting chapter

* Revised the divide and conquer chapter

* Revised the chapter backtacking

* Revised the DP chapter

* Revised the greedy chapter

* Revised the appendix chapter

* Revised the preface chapter doubly

* Revised the figures
2023-12-02 06:21:34 +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
/* 广 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))
}
}