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_adjacency_list.swift

122 lines
3.3 KiB

/**
* File: graph_adjacency_list.swift
* Created Time: 2023-02-01
* Author: nuomi1 (nuomi1@qq.com)
*/
import utils
/* */
class GraphAdjList {
// 使
// adjList Vertex
private var adjList: [Vertex: [Vertex]]
/* */
init(edges: [[Vertex]]) {
adjList = [:]
//
for edge in edges {
addVertex(vet: edge[0])
addVertex(vet: edge[1])
addEdge(vet1: edge[0], vet2: edge[1])
}
}
/* */
func size() -> Int {
adjList.count
}
/* */
func addEdge(vet1: Vertex, vet2: Vertex) {
if adjList[vet1] == nil || adjList[vet2] == nil || vet1 == vet2 {
fatalError("参数错误")
}
// vet1 - vet2
adjList[vet1]?.append(vet2)
adjList[vet2]?.append(vet1)
}
/* */
func removeEdge(vet1: Vertex, vet2: Vertex) {
if adjList[vet1] == nil || adjList[vet2] == nil || vet1 == vet2 {
fatalError("参数错误")
}
// vet1 - vet2
adjList[vet1]?.removeAll(where: { $0 == vet2 })
adjList[vet2]?.removeAll(where: { $0 == vet1 })
}
/* */
func addVertex(vet: Vertex) {
if adjList[vet] != nil {
return
}
//
adjList[vet] = []
}
/* */
func removeVertex(vet: Vertex) {
if adjList[vet] == nil {
fatalError("参数错误")
}
// vet
adjList.removeValue(forKey: vet)
// vet
for key in adjList.keys {
adjList[key]?.removeAll(where: { $0 == vet })
}
}
/* */
func print() {
Swift.print("邻接表 =")
for entry in adjList {
var tmp: [Int] = []
for vertex in entry.value {
tmp.append(vertex.val)
}
Swift.print("\(entry.key.val): \(tmp),")
}
}
}
@main
enum GraphAdjacencyList {
/* Driver Code */
static func main() {
/* */
let v = Vertex.valsToVets([1, 3, 2, 5, 4])
let edges = [[v[0], v[1]], [v[0], v[3]], [v[1], v[2]], [v[2], v[3]], [v[2], v[4]], [v[3], v[4]]]
let graph = GraphAdjList(edges: edges)
print("\n初始化后,图为")
graph.print()
/* */
// 1, 2 v[0], v[2]
graph.addEdge(vet1: v[0], vet2: v[2])
print("\n添加边 1-2 后,图为")
graph.print()
/* */
// 1, 3 v[0], v[1]
graph.removeEdge(vet1: v[0], vet2: v[1])
print("\n删除边 1-3 后,图为")
graph.print()
/* */
let v5 = Vertex(val: 6)
graph.addVertex(vet: v5)
print("\n添加顶点 6 后,图为")
graph.print()
/* */
// 3 v[1]
graph.removeVertex(vet: v[1])
print("\n删除顶点 3 后,图为")
graph.print()
}
}