알고리즘 풀이/프로그래머스
[level3] 프로그래머스 - 네트워크(JAVA)
데롱디롱
2021. 9. 14. 14:25
728x90
- 1~n개의 네트워크에 대해 탐색한다. => dfs
- 만약 연결된 네트워크중에 탐색하지 않은게 있다면, 계속해서 타고 들어가 탐색을 계속한다.
class Solution {
static boolean[] isVisited;
public int solution(int n, int[][] computers) {
int answer = 0;
isVisited = new boolean[n]; // 방문 처리
for(int i = 0; i < n; i++) {
if(!isVisited[i]) {
dfs(i, computers);
answer++;
}
}
return answer;
}
static void dfs(int cur, int[][] computers) {
isVisited[cur] = true;
for(int j = 0; j < computers.length; j++) {
if(!isVisited[j] && computers[cur][j] == 1) {
dfs(j, computers);
}
}
}
}