hello-algo/codes/swift/chapter_graph/graph_bfs.swift
nuomi1 c6c4c9d997
feat: add Swift codes for graph_traversal article (#378)
* feat: add Swift codes for graph_traversal article

* refactor: rename parameters

* Update graph_dfs.swift

---------

Co-authored-by: Yudong Jin <krahets@163.com>
2023-02-22 19:41:31 +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))
}
}