본문 바로가기
Preparing Coding Test/Programmers L3

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

by weero 2020. 10. 29.

문제

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;
    }
}