문제 링크: https://programmers.co.kr/learn/courses/30/lessons/43162
딱 보자마자 "이건 DFS
로 접근하는 문제다"라고 생각이 들꺼다.
그 다음은 분리되어 있는 그룹의 갯수를 카운팅하는 법을 생각했다.
-> 0
번부터 돌고 그 다음은 다음 루트 노드를 찾아서 또 돌면서 갯수를 증가시키면 된다.
import java.util.Stack;
class Solution {
public int solution(int n, int[][] computers) {
int count = 0;
boolean[] visit = new boolean[n];
Stack<Integer> stack = new Stack<>();
int curNode;
int[] connectInfo;
while ((curNode = findNextRootIndex(visit)) > -1) {
stack.push(curNode);
while (!stack.isEmpty()) {
curNode = stack.pop();
visit[curNode] = true;
connectInfo = computers[curNode];
for (int i = 0; i < connectInfo.length; i++) {
if (i != curNode && connectInfo[i] == 1 && !visit[i]) {
stack.push(i);
}
}
}
count++;
}
return count;
}
public int findNextRootIndex(boolean[] visit) {
for (int i = 0; i < visit.length; i++) {
if (!visit[i]) {
return i;
}
}
return -1;
}
}