개발자를 향해...

프로그래머스 - 네트워크 (java) 본문

코테 공부/프로그래머스master

프로그래머스 - 네트워크 (java)

eugeneHwang1124 2022. 4. 10. 17:42
728x90
반응형

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

 

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

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

programmers.co.kr

 

bfs로 문제를 풀었다. 

visited함수를 bfs 내에서만 쓰는게 아니라 for문을 통해 전체를 돌면서 방문하지 않는것이 있는지 확인하고 bfs를 그만큼 도는데에 썼다.

 

import java.util.*;
class Solution {
    public static boolean[]  visited ;
    public static int N;
    public int solution(int n, int[][] computers) {
        int answer = 0;
        N =n;
        visited = new boolean[n+1];
        int count = 0;
        for(int start = 0; start<N; start++){
            if(!visited[start]){ 
                bfs(computers, start); 
                count++;
            }
        }
        answer=count;
        return answer;
    }
    
    public static void bfs(int[][] computers, int start){
        Queue<Integer> queue = new LinkedList<Integer>();
        queue.offer(start);
        while (!queue.isEmpty()){
            int com = queue.poll();
            
            visited[com] = true;
            for(int i = 0; i<N; i++){
                if(computers[com][i]==1 && visited[i]==false){
                    queue.offer(i);
                }
            }
        }
    }
}

 

반응형