반응형
https://school.programmers.co.kr/learn/courses/30/lessons/43162
프로그래머스
SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr



내 코드
func dfs(_ node: Int, visited: inout [Bool], graph: inout [[Int]]) { visited[node] = true for next in graph[node] { if !visited[next] { dfs(next, visited: &visited, graph: &graph) } } } func solution(_ n: Int, _ computers: [[Int]]) -> Int { var graph = Array(repeating: [Int](), count: n + 1) var visited = Array(repeating: false, count: n + 1) var result: Int = 0 for i in 0..<n { for j in 0..<n { if computers[i][j] == 1 && i != j { graph[i + 1].append(j + 1) } } } for i in 1...n { if !visited[i] { result += 1 dfs(i, visited: &visited, graph: &graph) } } return result }
Review
1부터 n까지 for 문을 돌려서, 방문을 안 한 노드가 있으면 result += 1을 해주는 방법으로 문제를 해결했습니다.
dfs함수는 일반적인 깊이우선탐색 알고리즘과 같아서 생략하겠습니다.
dfs함수의 매개변수를 줄이고 싶다면, 아래처럼 solution 함수 내에 함수를 작성하면 됩니다.
func solution(_ n: Int, _ computers: [[Int]]) -> Int { var graph = Array(repeating: [Int](), count: n + 1) var visited = Array(repeating: false, count: n + 1) var result: Int = 0 for i in 0..<n { for j in 0..<n { if computers[i][j] == 1 && i != j { graph[i + 1].append(j + 1) } } } func dfs(_ node: Int) { visited[node] = true for next in graph[node] { if !visited[next] { dfs(next) } } } for i in 1...n { if !visited[i] { result += 1 dfs(i) } } return result }
반응형
'프로그래머스' 카테고리의 다른 글
[프로그래머스] 기지국 설치 Swift (0) | 2025.02.04 |
---|---|
[프로그래머스] 숫자 게임 Swift (1) | 2025.02.03 |
[프로그래머스] 행렬의 곱셈 Swift (1) | 2024.11.07 |
[프로그래머스] 귤 고르기 Swift (3) | 2024.10.28 |
[프로그래머스] H-Index Swift (0) | 2024.08.15 |