1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
|
import java.util.*;
class Solution {
// 방문 배열 선언
static boolean[] visited;
// 인접리스트 선언
static List<List<Integer>> list;
public int solution(int n, int[][] computers) {
// 연결된 네트워크 개수를 셀 변수
int answer = 0;
// 방문 배열 초기화
visited = new boolean[n+1];
// 인접리스트 초기화
list = new ArrayList<>();
for(int i=0; i<=n; i++) {
list.add(new ArrayList<>());
}
// 인접리스트 구현
for(int i=0; i<computers.length; i++) {
for(int j=0; j<computers.length; j++) {
if(i != j) {
if(computers[i][j] == 1) {
list.get(i+1).add(j+1);
}
}
}
}
// n까지 순회하면서 DFS 재귀함수 호출
// 방문하지 않은 노드라면 연결되어 있지 않는 네트워크라고 판단하여 answer 카운트 1 증가
for(int i=1; i<=n; i++) {
if(!visited[i]) {
answer++;
}
DFS(i);
}
return answer;
}
// DFS 재귀함수 구현
// 방문한 노드라면 연결되어 있는 네트워크이기에 넘어가고 해당 노드와 연결된 노드에서 방문하지 않은 노드를 재귀호출하여 탐색한다.
static void DFS(int node) {
if(visited[node]) {
return;
}
visited[node] = true;
for(int next : list.get(node)) {
if(!visited[next]) {
DFS(next);
}
}
}
public static void main(String[] args) {
Solution sol = new Solution();
int n = 3;
int[][] computers = new int[][]{{1,1,0}, {1,1,0}, {0,0,1}};
// int[][] computers = new int[][]{{1,1,0}, {1,1,1}, {0,1,1}};
sol.solution(n, computers);
}
}
|