forked from kodecocodes/swift-algorithm-club
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Graph.swift
51 lines (41 loc) · 1.12 KB
/
Graph.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
public class Graph: CustomStringConvertible {
public typealias Node = String
private(set) public var adjacencyLists: [Node : [Node]]
public init() {
adjacencyLists = [Node: [Node]]()
}
public func addNode(_ value: Node) -> Node {
adjacencyLists[value] = []
return value
}
public func addEdge(fromNode from: Node, toNode to: Node) -> Bool {
adjacencyLists[from]?.append(to)
return adjacencyLists[from] != nil ? true : false
}
public var description: String {
return adjacencyLists.description
}
public func adjacencyList(forNode node: Node) -> [Node]? {
for (key, adjacencyList) in adjacencyLists {
if key == node {
return adjacencyList
}
}
return nil
}
}
extension Graph {
typealias InDegree = Int
func calculateInDegreeOfNodes() -> [Node : InDegree] {
var inDegrees = [Node: InDegree]()
for (node, _) in adjacencyLists {
inDegrees[node] = 0
}
for (_, adjacencyList) in adjacencyLists {
for nodeInList in adjacencyList {
inDegrees[nodeInList] = (inDegrees[nodeInList] ?? 0) + 1
}
}
return inDegrees
}
}