문제
programmers.co.kr/learn/courses/30/lessons/43162
코딩테스트 연습 - 네트워크
네트워크란 컴퓨터 상호 간에 정보를 교환할 수 있도록 연결된 형태를 의미합니다. 예를 들어, 컴퓨터 A와 컴퓨터 B가 직접적으로 연결되어있고, 컴퓨터 B와 컴퓨터 C가 직접적으로 연결되어 있
programmers.co.kr
코드
import java.util.*;
class Solution {
static boolean[] visited;
static int cnt;
public static void bfs(int start, ArrayList<Integer>[] adjacent){
Queue<Integer> q = new LinkedList<Integer>();
q.offer(start);
cnt++;
while(!q.isEmpty()){
int f = q.poll();
visited[f] = true;
for(int e : adjacent[f]){
if(!visited[e]){
q.offer(e);
visited[e] = true;
}
}
}
}
public static int solution(int n, int[][] computers) {
int answer = 0;
ArrayList<Integer>[] adjacent = new ArrayList[n+1];
visited = new boolean[n+1];
cnt = 0;
for(int i=1; i<=n; i++) {
adjacent[i] = new ArrayList<Integer>();
}
for(int i=1; i<=n; i++){
for(int j=0; j<n; j++){
if(i-1 != j && computers[i-1][j]==1){
adjacent[i].add(j+1);
adjacent[j+1].add(i);
}
}
}
for(int i=1; i<=n; i++){
if(!visited[i]){
bfs(i, adjacent);
}
}
return answer=cnt;
}
}
'Preparing Coding Test > Programmers L3' 카테고리의 다른 글
[Java/프로그래머스/해시] Level 3: 베스트앨범 (0) | 2020.12.06 |
---|---|
[Java/프로그래머스/DFS] Level 3: 단어 변환 (0) | 2020.11.06 |
[Java/프로그래머스/DFS] 여행경로 (0) | 2020.11.05 |
[Java/프로그래머스/힙(Heap)] 이중우선순위큐 (0) | 2020.10.27 |
[Java/프로그래머스/힙(Heap)] 디스크 컨트롤러 (0) | 2020.10.20 |