https://school.programmers.co.kr/learn/courses/30/lessons/43162
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
커넥티드 컴포넌트
1. 연결되어 있는 노드들을 2차원 List에 담는다.
2. 1번노드부터, 연결된 노드들을 탐방하면서 방문처리를 해준다.
3. dfs()가 한번 끝난경우 == 한 네트워크를 의미하므로, 방문되지 않은 다음 노드(네트워크)를 dfs() 돌려준다.
풀이 코드
import java.util.*;
class Solution {
public int[] visited;
public List<List<Integer>> list;
public int solution(int n, int[][] computers) {
int answer = 0;
list = new ArrayList<>();
visited = new int[n];
for(int i = 0; i < computers.length; i++){
list.add(new ArrayList<>());
for(int j = 0; j < computers[i].length; j++){
if(computers[i][j] == 1 && i!=j){
list.get(i).add(j);
}
}
}
for(int i = 0; i < n; i++){
if(visited[i] == 0) {
visited[i] = 1; // 자기 자신 방문 처리
dfs(i);
answer++;
}
}
return answer;
}
public void dfs(int next) {
for(int value: list.get(next)) {
if(visited[value] == 0){
visited[value] = 1;
dfs(value);
}
}
}
}
실행 결과
'Backend > 알고리즘' 카테고리의 다른 글
[백준] 16234번 - 인구이동 (0) | 2024.05.28 |
---|---|
[프로그래머스] Lv3. 야근 지수 (0) | 2024.05.28 |
[프로그래머스] Lv2. 주식가격 (0) | 2024.05.28 |
[프로그래머스] Lv.2 모음 사전 (0) | 2024.05.28 |
[프로그래머스] Lv.2 게임 맵 최단거리 (0) | 2024.05.28 |