ALGORITHM
[JAVA] [프로그래머스] Level 2 - DFS/BFS - 네트워크
printf100
2020. 10. 19. 23:24
programmers.co.kr/learn/courses/30/lessons/43162
코딩테스트 연습 - 네트워크
네트워크란 컴퓨터 상호 간에 정보를 교환할 수 있도록 연결된 형태를 의미합니다. 예를 들어, 컴퓨터 A와 컴퓨터 B가 직접적으로 연결되어있고, 컴퓨터 B와 컴퓨터 C가 직접적으로 연결되어 있��
programmers.co.kr



class Solution {
public int solution(int n, int[][] computers) {
int answer = 0;
boolean[] visited = new boolean[n];
for(int i=0; i<n; i++) {
visited[i] = false; // 모두 방문하지 않은 곳으로 셋팅
}
for(int i=0; i<n; i++) {
if(!visited[i]) {
dfs(computers, visited, i);
answer++;
}
}
return answer;
}
public void dfs(int[][] computers, boolean[] visited, int index) {
visited[index] = true; // 방문
for(int i=0; i<computers.length; i++) {
// 아직 방문하지 않음, 연결된 곳, 자신 제외
if(!visited[i] && computers[index][i] == 1 && index != i)
dfs(computers, visited, i);
}
}
}