본문 바로가기
알고리즘/프로그래머스

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

by hxxyeoniii 2024. 11. 20.

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

 

프로그래머스

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

programmers.co.kr


문제 풀이

bfs를 활용해 그래프의 연결을 확인한다.

import java.util.*;

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