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

131 lines
3.7 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

/**
* File: graph_adjacency_matrix.swift
* Created Time: 2023-02-01
* Author: nuomi1 (nuomi1@qq.com)
*/
import utils
/* */
class GraphAdjMat {
private var vertices: [Int] //
private var adjMat: [[Int]] //
/* */
init(vertices: [Int], edges: [[Int]]) {
self.vertices = []
adjMat = []
//
for val in vertices {
addVertex(val: val)
}
//
// edges vertices
for e in edges {
addEdge(i: e[0], j: e[1])
}
}
/* */
func size() -> Int {
vertices.count
}
/* */
func addVertex(val: Int) {
let n = size()
//
vertices.append(val)
//
let newRow = Array(repeating: 0, count: n)
adjMat.append(newRow)
//
for i in adjMat.indices {
adjMat[i].append(0)
}
}
/* */
func removeVertex(index: Int) {
if index >= size() {
fatalError("越界")
}
// index
vertices.remove(at: index)
// index
adjMat.remove(at: index)
// index
for i in adjMat.indices {
adjMat[i].remove(at: index)
}
}
/* */
// i, j vertices
func addEdge(i: Int, j: Int) {
//
if i < 0 || j < 0 || i >= size() || j >= size() || i == j {
fatalError("越界")
}
// 线 (i, j) == (j, i)
adjMat[i][j] = 1
adjMat[j][i] = 1
}
/* */
// i, j vertices
func removeEdge(i: Int, j: Int) {
//
if i < 0 || j < 0 || i >= size() || j >= size() || i == j {
fatalError("越界")
}
adjMat[i][j] = 0
adjMat[j][i] = 0
}
/* */
func print() {
Swift.print("顶点列表 = ", terminator: "")
Swift.print(vertices)
Swift.print("邻接矩阵 =")
PrintUtil.printMatrix(matrix: adjMat)
}
}
@main
enum GraphAdjacencyMatrix {
/* Driver Code */
static func main() {
/* */
// edges vertices
let vertices = [1, 3, 2, 5, 4]
let edges = [[0, 1], [1, 2], [2, 3], [0, 3], [2, 4], [3, 4]]
let graph = GraphAdjMat(vertices: vertices, edges: edges)
print("\n初始化后,图为")
graph.print()
/* */
// 1, 2 0, 2
graph.addEdge(i: 0, j: 2)
print("\n添加边 1-2 后,图为")
graph.print()
/* */
// 1, 3 0, 1
graph.removeEdge(i: 0, j: 1)
print("\n删除边 1-3 后,图为")
graph.print()
/* */
graph.addVertex(val: 6)
print("\n添加顶点 6 后,图为")
graph.print()
/* */
// 3 1
graph.removeVertex(index: 1)
print("\n删除顶点 3 后,图为")
graph.print()
}
}