Algorithm/프로그래머스
[고득점kit][DFS][lv.3] 네트워크 - 자바(Java)
sdoaolo
2022. 12. 7. 10:14
728x90
프로그래머스 > 코딩테스트 연습 > 코딩테스트 고득점kit > 깊이/너비 우선 탐색(DFS/BFS) > 네트워크
문제 링크
https://school.programmers.co.kr/learn/courses/30/lessons/43162
문제
문제 설명
네트워크란 컴퓨터 상호 간에 정보를 교환할 수 있도록 연결된 형태를 의미합니다. 예를 들어, 컴퓨터 A와 컴퓨터 B가 직접적으로 연결되어있고, 컴퓨터 B와 컴퓨터 C가 직접적으로 연결되어 있을 때 컴퓨터 A와 컴퓨터 C도 간접적으로 연결되어 정보를 교환할 수 있습니다. 따라서 컴퓨터 A, B, C는 모두 같은 네트워크 상에 있다고 할 수 있습니다.
컴퓨터의 개수 n, 연결에 대한 정보가 담긴 2차원 배열 computers가 매개변수로 주어질 때, 네트워크의 개수를 return 하도록 solution 함수를 작성하시오.
제한사항- 컴퓨터의 개수 n은 1 이상 200 이하인 자연수입니다.
- 각 컴퓨터는 0부터 n-1인 정수로 표현합니다.
- i번 컴퓨터와 j번 컴퓨터가 연결되어 있으면 computers[i][j]를 1로 표현합니다.
- computer[i][i]는 항상 1입니다.
아무리 고득점kit라고 해도 이게 왜 레벨 3인지 모르겠다음...
✅ 내가 쓴 정답코드
class Solution {
public int solution(int n, int[][] computers) {
int answer = 0;
//네트워크의 개수를 리턴하시오
int length = computers.length;
int [] visited = new int[length];
for(int i=0; i<length; i++ ){
if (visited[i] == 0) {
dfs(i, computers, visited);
answer++;
}
}
return answer;
}
public void dfs(int node, int[][]computers, int[]visited) {
visited[node] = 1;
//node와 연결된 컴퓨터 찾기
for(int i=0 ; i<computers.length; i++) {
if (visited[i] == 0 && computers[node][i] == 1) {
dfs(i,computers, visited);
}
}
return;
}
}
references
더보기
프로그래머스