https://school.programmers.co.kr/learn/courses/30/lessons/43162
프로그래머스
SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
자바
public class Solution {
public int solution(int n, int[][] computers) {
boolean[] visited = new boolean[n];
int count = 0;
for (int i = 0; i < n; i++) {
if (!visited[i]) {
dfs(computers, visited, i);
count++;
}
}
return count;
}
private void dfs(int[][] computers, boolean[] visited, int node) {
visited[node] = true;
for (int i = 0; i < computers.length; i++) {
if (computers[node][i] == 1 && !visited[i]) {
dfs(computers, visited, i);
}
}
}
}
파이썬
def solution(n, computers):
def dfs(node):
visited[node] = True
for neighbor in range(n):
if computers[node][neighbor] == 1 and not visited[neighbor]:
dfs(neighbor)
visited = [False] * n
count = 0
for i in range(n):
if not visited[i]:
dfs(i)
count += 1
return count
# Example usage
n = 3
computers = [[1, 1, 0], [1, 1, 0], [0, 0, 1]]
print(solution(n, computers))
'Portpolio > codingtest' 카테고리의 다른 글
프로그래머스 Lv3. 야근 지수 풀이 (0) | 2025.03.21 |
---|---|
프로그래머스 커피 심부름 풀이 (0) | 2025.02.26 |
프로그래머스 수 나누기 풀이 (0) | 2025.02.26 |
프로그래머스 각도 합치기 풀이 (0) | 2025.02.26 |
프로그래머스 문자 출력 풀이 (0) | 2025.02.26 |
댓글