문제
https://school.programmers.co.kr/learn/courses/30/lessons/43162
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
접근 방법 및 풀이
0번째 컴퓨터부터 n-1번째 컴퓨터까지 연결된 컴퓨터를 순회하는데 순회 할 때 방문 여부를 체크
i번째 컴퓨터에서 순회를 시작 하기 전 해당 컴퓨터를 방문하지 않은 경우에만 순회를 시작
순회가 일어난 횟수가 네트워크의 구성 수
public class Q30_43162 {
public int solution(int n, int[][] computers) {
boolean[] visits = new boolean[n]; // 방문 여부를 확인 할 배열
int answer = 0;
for (int i = 0; i < n; i++) {
if (!visits[i]) { // 방문 한적 없는 컴퓨터
visit(computers, i, visits);
answer++;
}
}
return answer;
}
// node 컴퓨터를 시작으로 방문할 수 있는 컴퓨터들을 순회하고 방문 여부를 체크
public void visit(int[][] computers, int node, boolean[] visits) {
visits[node] = true; // node에 방문 체크
int[] destinations = computers[node];
int length = destinations.length;
for (int i = 0; i < length; i++) {
if (!visits[i] && destinations[i] == 1) { // 방문한적이 없으면서 네트워크가 연결된 컴퓨터
visit(computers, i, visits);
}
}
}
}