STUDY/Coding
[프로그래머스] 네트워크
sohexz
2024. 3. 22. 11:08
[프로그래머스] 네트워크 문제풀이 (Java)
[프로그래머스] 네트워크 문제풀이 (Java)
velog.io
재귀함수를 통한 DFS
참고한 풀이
class Solution {
public int solution(int n, int[][] computers) {
int answer = 0;
boolean[] visited = new boolean[n];
for(int i=0; i<n; i++){
if(!visited[i]){
dfs(computers, visited, i);
answer++;
}
}
return answer;
}
public void dfs(int[][]computers, boolean[]visited, int v){
visited[v] = true;
for(int j=0; j<computers.length; j++){
if(computers[v][j]==1 && !visited[j]){
dfs(computers, visited, j);
}
}
}
}