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>
This commit is contained in:
nuomi1
2023-02-22 19:41:31 +08:00
committed by GitHub
parent f2d2cca5f1
commit c6c4c9d997
7 changed files with 136 additions and 13 deletions
@@ -7,13 +7,13 @@
import utils
/* */
class GraphAdjList {
public class GraphAdjList {
// 使
// adjList Vertex
private var adjList: [Vertex: [Vertex]]
public private(set) var adjList: [Vertex: [Vertex]]
/* */
init(edges: [[Vertex]]) {
public init(edges: [[Vertex]]) {
adjList = [:]
//
for edge in edges {
@@ -24,12 +24,12 @@ class GraphAdjList {
}
/* */
func size() -> Int {
public func size() -> Int {
adjList.count
}
/* */
func addEdge(vet1: Vertex, vet2: Vertex) {
public func addEdge(vet1: Vertex, vet2: Vertex) {
if adjList[vet1] == nil || adjList[vet2] == nil || vet1 == vet2 {
fatalError("参数错误")
}
@@ -39,7 +39,7 @@ class GraphAdjList {
}
/* */
func removeEdge(vet1: Vertex, vet2: Vertex) {
public func removeEdge(vet1: Vertex, vet2: Vertex) {
if adjList[vet1] == nil || adjList[vet2] == nil || vet1 == vet2 {
fatalError("参数错误")
}
@@ -49,7 +49,7 @@ class GraphAdjList {
}
/* */
func addVertex(vet: Vertex) {
public func addVertex(vet: Vertex) {
if adjList[vet] != nil {
return
}
@@ -58,7 +58,7 @@ class GraphAdjList {
}
/* */
func removeVertex(vet: Vertex) {
public func removeVertex(vet: Vertex) {
if adjList[vet] == nil {
fatalError("参数错误")
}
@@ -71,7 +71,7 @@ class GraphAdjList {
}
/* */
func print() {
public func print() {
Swift.print("邻接表 =")
for entry in adjList {
var tmp: [Int] = []
@@ -83,12 +83,14 @@ class GraphAdjList {
}
}
#if !TARGET
@main
enum GraphAdjacencyList {
/* Driver Code */
static func main() {
/* */
let v = Vertex.valsToVets([1, 3, 2, 5, 4])
let v = Vertex.valsToVets(vals: [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初始化后,图为")
@@ -119,3 +121,5 @@ enum GraphAdjacencyList {
graph.print()
}
}
#endif