https://school.programmers.co.kr/learn/courses/30/lessons/43162
문제 포인트
DFS를 사용해서 몇번 순환 하는지 체크하는 어렵지 않은 문제였다. computers 배열에서 computers[i][i] 인 경우 1로 초기화가 되있기 때문에 모두 0으로 바꾸어 주고, 1이거나 방문하지 않았던 컴퓨터를 계속 DFS로 방문하여 몇번 싸이클이 도는지 answer 변수에 추가해주면 되는 단순한 DFS 문제였다.
DFS 함수안에서
if(visited[i])
return;
하는 경우와 (보통 백트래킹)
visited[i] = true;
이런 경우를 잘 구분해서 사용해야 할 것 같다.
class Solution {
static int N;
static boolean[] visited;
public int solution(int n, int[][] computers) {
int answer = 0;
N = n;
visited = new boolean[N];
for (int i = 0; i < N; i++)
computers[i][i] = 0;
for (int i = 0; i < N; i++) {
if (!visited[i]) {
DFS(i, computers);
answer++;
}
}
return answer;
}
public void DFS(int n, int[][] computers) {
visited[n] = true;
for (int i = 0; i < N; i++) {
if (!visited[i] && computers[n][i] == 1) {
DFS(i, computers);
}
}
}
}
'프로그래밍 & IT > Algorithm' 카테고리의 다른 글
[알고리즘] 프로그래머스 괄호 변환 :: 우유 (0) | 2023.04.06 |
---|---|
[알고리즘] 프로그래머스 [3차] 방금그곡 :: 우유 (0) | 2023.04.05 |
[알고리즘] 프로그래머스 여행경로 :: 우유 (0) | 2023.04.03 |
[알고리즘] 프로그래머스 정수 삼각형 :: 우유 (0) | 2023.03.23 |
[알고리즘] 프로그래머스 캐시 :: 우유 (0) | 2022.10.10 |