ALGORITHM/PROGRAMMERS

[프로그래머스] 네트워크

0298 2021. 4. 15. 16:37

programmers.co.kr/learn/courses/30/lessons/43162

 

코딩테스트 연습 - 네트워크

네트워크란 컴퓨터 상호 간에 정보를 교환할 수 있도록 연결된 형태를 의미합니다. 예를 들어, 컴퓨터 A와 컴퓨터 B가 직접적으로 연결되어있고, 컴퓨터 B와 컴퓨터 C가 직접적으로 연결되어 있

programmers.co.kr

2021-04-15


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
 
public class Solution43162 {
    public static int solution(int n, int[][] computers) {
        int answer = 0;
        List<List<Integer>> list = new ArrayList<>();
        //init
        for(int i = 0; i < n; i++) list.add(new ArrayList<>());
 
        for(int i = 0; i < n; i++) {
            for(int j = i+1; j < n; j++) {
                if(computers[i][j] == 1) {
                    list.get(i).add(j);
                    list.get(j).add(i);
                }
            }
        }
 
        boolean vtd[] = new boolean[n];
 
        Queue<Integer> q = new LinkedList<>();
        for(int i = 0; i < n; i++) {
            if(!vtd[i]) {
                q.add(i);
                vtd[i] = true;
                while(!q.isEmpty()) {
                    int x = q.poll();
 
                    for(int value: list.get(x)) {
                        if(!vtd[value]){
                            q.add(value);
                            vtd[value] = true;
                        }
                    }
                }
                answer++;
            }
        }
 
        return answer;
    }
    public static void main(String[] args) {
        int n = 3;
        int[][] com = {{110}, {110}, {001}};
        System.out.println(solution(n, com));
    }
}
cs

#문제풀이

 

연결 가능한 컴퓨터들 체크해주고 연결되어 있는 컴퓨터들을 하나의 네트워크로 카운트 해주었다.