-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1192. Critical Connections in a Network.swift
111 lines (61 loc) · 2.24 KB
/
1192. Critical Connections in a Network.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import Foundation
class Solution {
private func initGraph(connections: Array<Array<Int>>, ignore: Array<Int>) -> [Int: Array<Int>] {
var graph: [Int: Array<Int>] = [:]
for connection in connections {
if(connection == ignore){
continue
}
if graph[connection[0]] == nil {
graph[connection[0]] = [connection[1]]
}
else{
graph[connection[0]]!.append(connection[1])
}
if graph[connection[1]] == nil {
graph[connection[1]] = [connection[0]]
}
else{
graph[connection[1]]!.append(connection[0])
}
}
return graph
}
private func depthFirstSearch(_ node: Int,graph: [Int: Array<Int>]) -> Int{
var stack: Array<Int> = []
var alreadyVisited: Set<Int> = []
//
alreadyVisited.insert(node)
stack.append(node)
var count: Int = 1
while(stack.count > 0){
let current = stack.removeLast()
let edges = graph[current]!
for edge in edges {
if(!alreadyVisited.contains(edge)){
alreadyVisited.insert(edge)
stack.append(edge)
count += 1
}
}
}
return count
}
func criticalConnections(_ n: Int, _ connections: [[Int]]) -> [[Int]] {
var result: Array<Array<Int>> = []
if(n == 2){
return connections
}
for connection in connections {
let graph = initGraph(connections: connections,ignore: connection)
if(depthFirstSearch(0, graph: graph) != n){
result.append(connection)
}
}
return result
}
}
var solution = Solution()
let edges = [[0,1],[1,2],[2,0],[1,3]]
var result = solution.criticalConnections(2, edges)
print(result)