프로그래머스 / 네트워크 / java

맹민재·2023년 7월 18일
0

Java

목록 보기
27/32
import java.util.*;
class Solution {
    public int solution(int n, int[][] computers) {
        int answer = 0;
        boolean[] visited = new boolean[n];
        int[][] graph = new int[n][n];
        for(int i=0; i<n;i++){
            for(int j=0; j<n;j++){
                if(i != j & computers[i][j] == 1)
                    graph[i][j] = 1;
            }
        }
        
        for(int i=0; i<n;i++){
            if(!visited[i]){
                answer++;
                Deque<Integer> q = new LinkedList<>();
                q.add(i);
                
                while(!q.isEmpty()){
                    int node = q.peek();
                    q.poll();
                    
                    visited[node] = true;
                    
                    for(int j=0;j<n;j++){
                        if(graph[node][j]==1 & !visited[j]){
                            visited[j] = true;
                            q.add(j);
                        }
                    }
                    
                }
            }
        }
        
        return answer;
    }
}

bfs로 해결한 문제
bfs, dfs 둘 다 상관 없는 문제

profile
ㄱH ㅂrㄹ ㅈr

0개의 댓글