-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.swift
71 lines (68 loc) · 1.71 KB
/
main.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
//
// main.swift
// SwiftAlgorithm
//
// Created by Lee Myeonghwan on 2023/02/03.
//
import Foundation
// DFS
func solution(_ n:Int, _ computers:[[Int]]) -> Int {
var connectMap: [[Int]] = Array(repeating: Array(repeating: 0, count: n), count: n)
var isVisited: [Bool] = Array(repeating: false, count: n)
var cnt = 0
for i in 0..<n {
for j in 0..<n {
if computers[i][j] == 1 {
connectMap[i][j] = 1
}
}
}
func DFS(node: Int) {
for idx in 0..<n {
if !isVisited[idx] && connectMap[node][idx] == 1 {
isVisited[idx] = true
DFS(node: idx)
}
}
}
for i in 0..<n {
if !isVisited[i] {
isVisited[i] = true
cnt += 1
DFS(node: i)
}
}
return cnt
}
/* BFS
func solution(_ n:Int, _ computers:[[Int]]) -> Int {
var connectMap: [[Int]] = Array(repeating: Array(repeating: 0, count: n), count: n)
var isVisited: [Bool] = Array(repeating: false, count: n)
var cnt = 0
for i in 0..<n {
for j in 0..<n {
if computers[i][j] == 1 {
connectMap[i][j] = 1
}
}
}
var queue: [Int] = []
for i in 0..<n {
if !isVisited[i] {
queue.append(i)
cnt += 1
isVisited[i] = true
while !queue.isEmpty {
let node = queue.removeFirst()
for k in 0..<n {
if !isVisited[k] && connectMap[node][k] == 1 {
isVisited[k] = true
queue.append(k)
}
}
}
}
}
return cnt
}
*/