Files
hello-algo/ja/codes/swift/chapter_graph/graph_adjacency_matrix.swift
Yudong Jin d7b2277d2b Re-translate the Japanese version (#1871)
* Retranslate Japanese docs with GPT-5.4

* Retranslate Japanese code with GPT-5.4
2026-03-30 07:30:15 +08:00

131 lines
4.1 KiB
Swift
Raw Permalink 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_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)
// 1
let newRow = Array(repeating: 0, count: n)
adjMat.append(newRow)
// 1
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()
}
}