https://school.programmers.co.kr/learn/courses/30/lessons/43162

 

프로그래머스

SW개발자를 위한 평가, 교육의 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr


문제

문제 설명
네트워크란 컴퓨터 상호 간에 정보를 교환할 수 있도록 연결된 형태를 의미합니다. 예를 들어, 컴퓨터 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입니다.
입출력 예
n computers return
3 [[1, 1, 0], [1, 1, 0], [0, 0, 1]] 2
3 [[1, 1, 0], [1, 1, 1], [0, 1, 1]] 1


문제 해결을 위한 과정

 

  • 그래프 구축: computers 인접 행렬 데이터를 ArrayList<ArrayList<Integer>> 인접 리스트로 변환합니다.
  • 전체 순회: 1번 컴퓨터부터 n번까지 차례대로 확인합니다.
  • 방문하지 않은 노드 탐색:
    • 아직 방문하지 않은 컴퓨터를 발견하면, 해당 지점에서 BFS를 시작합니다.
    • 한 번의 BFS가 끝나면, 그 시작점과 연결된 모든 컴퓨터는 visited 처리가 됩니다.
  • 카운트: BFS가 새롭게 시작되는 횟수가 곧 독립된 네트워크의 개수입니다.

 

 

소스코드
import java.util.*;

class Solution {
    static boolean[] visited;
    static ArrayList<ArrayList<Integer>> graph = new ArrayList<ArrayList<Integer>>();
    
    static void bfs(int start) {
        Queue<Integer> q = new LinkedList<>();
        visited[start] = true;
        q.offer(start);
        while(!q.isEmpty()) {
            int v = q.poll();
            System.out.print(v + " ");
            for(int i = 0; i < graph.get(v).size(); i++) {
                int y = graph.get(v).get(i);
                if(!visited[y]) {
                    visited[y] = true;
                    q.offer(y);
                }
            }
        }
    }
    public int solution(int n, int[][] computers) {
        int answer = 0;
        visited = new boolean[n + 1];
        for(int i = 0; i < n + 1; i++) {
            graph.add(new ArrayList<>());
        }
        
        for(int i = 0; i < computers.length; i++) {
            for(int j = 0; j < computers[i].length; j++) {
                if(i == j) {
                    continue;
                } else {
                    if(computers[i][j] == 1) {
                        graph.get(i+1).add(j+1);
                        graph.get(j+1).add(i+1);
                    }
                }
            }
        }
        
        for(int i = 1; i < n + 1; i++) {
            if(!visited[i]) {
                bfs(i);
                answer += 1;
            }
        }
        
        return answer;
    }
}

+ Recent posts