인접 리스트를 사용한 풀이
import Foundation
func solution(_ n:Int, _ computers:[[Int]]) -> Int {
var answer = 0
var graph: [[Int]] = Array(repeating: [], count: n)
var visited = Array(repeating: false, count: n)
for i in 0..<n {
for j in 0..<n {
if computers[i][j] == 1 && i != j {
graph[i].append(j)
graph[j].append(i)
}
}
}
func dfs(_ num: Int) {
visited[num] = true
for next in graph[num] {
if !visited[next] {
dfs(next)
}
}
}
for i in 0..<n {
if !visited[i] {
answer += 1
dfs(i)
}
}
return answer
}
인접 행렬을 사용한 풀이
import Foundation
func solution(_ n:Int, _ computers:[[Int]]) -> Int {
var answer = 0
var visited = Array(repeating: false, count: n)
func dfs(_ num: Int) {
visited[num] = true
for i in 0..<n {
if computers[num][i] == 1 && !visited[i] {
dfs(i)
}
}
}
for i in 0..<n {
if !visited[i] {
answer += 1
dfs(i)
}
}
return answer
}