[프로그래머스] 네트워크 - JAVA [자바]

doxxx·2023년 1월 25일
0

프로그래머스

목록 보기
7/17
post-thumbnail

링크

문제

네트워크란 컴퓨터 상호 간에 정보를 교환할 수 있도록 연결된 형태를 의미합니다. 예를 들어, 컴퓨터 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입니다.

알고리즘

각 노드(컴퓨터)에서 자기 자신을 제외하고, 다른 노드들과 연결되어 있는지를 체크하면 된다.

DFS, BFS 둘다 풀이가 가능하다.

풀이

DFS 풀이

class Solution {  
  
    boolean[] visited;  
  
    public int solution(int n, int[][] computers) {  
        visited = new boolean[n];  
        int answer = 0;  
        for (int i = 0; i < computers.length; i++) {  
            if (visited[i]) {  
                continue;  
            }  
            dfs(i, computers);  
            answer++;  
        }  
        return answer;  
    }  
  
    private void dfs(int i, int[][] computers) {  
        // 해당 노드를 방문 처리
        visited[i] = true;
        // 반복문을 순회하면서 j 번째 노드(컴퓨터)에 대해서
        // 1. 자기 자신이거나
        // 2. 연결되지 않았거나
        // 3. 이미 방문했거나
        // 위 3 조건에 대해서는 continue하고 dfs  
        for (int j = 0; j < computers.length; j++) {  
            if (i == j || computers[i][j] == 0 || visited[j]) {  
                continue;  
            }  
            dfs(j, computers);  
        }  
    }  
}

BFS 풀이

dfs랑 다를 바 없다.

class Solution {  
  
    boolean[] visited;  
    public int solution(int n, int[][] computers){  
        visited = new boolean[n];  
        int answer = 0;  
        for(int i = 0; i < computers.length; i++){  
            if(visited[i]){  
                continue;  
            }  
            bfs(i, computers);  
            answer++;  
        }  
        return answer;  
    }  
  
    private void bfs(int i, int[][] computers) {  
        Queue<Integer> queue = new LinkedList<>();  
        queue.add(i);  
        visited[i] = true;  
        while(!queue.isEmpty()){  
            int current = queue.poll();  
            for(int j = 0; j < computers.length; j++){  
                if(current == j || computers[current][j] == 0 || visited[j]){  
                    continue;  
                }  
                queue.add(j);  
                visited[j] = true;  
            }  
        }  
    }  
}

0개의 댓글