# andyRon/swift-algorithm-club-cn

Fetching latest commit…
Cannot retrieve the latest commit at this time.
Type Name Latest commit message Commit time
..
Failed to load latest commit information.
Graph
Images

# 图(Graph)

## 哦，我的点和边！

V 是图中点的数量，E 是边数。 然后我们有：

“检查邻接”意味着我们试图确定给定点是另一个点的直接邻居。 检查邻接表的邻接的时间是 O(V)，因为在最坏的情况下，点需要连接到每个其他点。

## 代码：边和点

```public struct Edge<T>: Equatable where T: Equatable, T: Hashable {

public let from: Vertex<T>
public let to: Vertex<T>

public let weight: Double?

}```

`Vertex`看起来像这样：

```public struct Vertex<T>: Equatable where T: Equatable, T: Hashable {

public var data: T
public let index: Int

}```

## 代码：图

```for graph in [AdjacencyMatrixGraph<Int>(), AdjacencyListGraph<Int>()] {

let v1 = graph.createVertex(1)
let v2 = graph.createVertex(2)
let v3 = graph.createVertex(3)
let v4 = graph.createVertex(4)
let v5 = graph.createVertex(5)

}```

```  graph.addUndirectedEdge(v1, to: v2, withWeight: 1.0)

## 代码：邻接表

```private class EdgeList<T> where T: Equatable, T: Hashable {

var vertex: Vertex<T>
var edges: [Edge<T>]? = nil

init(vertex: Vertex<T>) {
self.vertex = vertex
}

edges?.append(edge)
}

}```

```open override func createVertex(_ data: T) -> Vertex<T> {
// check if the vertex already exists
let matchingVertices = vertices.filter() { vertex in
return vertex.data == data
}

if matchingVertices.count > 0 {
return matchingVertices.last!
}

// if the vertex doesn't exist, create a new one
let vertex = Vertex(data: data, index: adjacencyList.count)
return vertex
}```

``````v1 -> [(v2: 1.0)]
v2 -> [(v3: 1.0), (v5: 3.2)]
v3 -> [(v4: 4.5)]
v4 -> [(v1: 2.8)]
``````

## 代码：邻接矩阵

```open override func createVertex(_ data: T) -> Vertex<T> {
// check if the vertex already exists
let matchingVertices = vertices.filter() { vertex in
return vertex.data == data
}

if matchingVertices.count > 0 {
return matchingVertices.last!
}

// if the vertex doesn't exist, create a new one
let vertex = Vertex(data: data, index: adjacencyMatrix.count)

// Expand each existing row to the right one column.
for i in 0 ..< adjacencyMatrix.count {
}

// Add one new row at the bottom.
let newRow = [Double?](repeating: nil, count: adjacencyMatrix.count + 1)

_vertices.append(vertex)

return vertex
}```

``````[[nil, 1.0, nil, nil, nil]    v1
[nil, nil, 1.0, nil, 3.2]    v2
[nil, nil, nil, 4.5, nil]    v3
[2.8, nil, nil, nil, nil]    v4
[nil, nil, nil, nil, nil]]   v5

v1   v2   v3   v4   v5
``````

## 扩展阅读

You can’t perform that action at this time.