programmers_가장 먼 노드_java

2023. 3. 6. 15:46Algorithm/Programmers

728x90

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

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

import java.util.*;
class Solution {
    public int solution(int n, int[][] edge) {
        int answer = 0;
        
        answer = bfs(n, edge);
        
        return answer;
    }
    
    public int bfs(int n, int[][] edge){
        int cnt = 0;
        
        List<Integer>[] map = new List[n+1];
        for(int i = 1; i<=n; i++){
            map[i] = new ArrayList<>();
        }
        
        int edgeSize = edge.length;
        for(int i = 0; i< edgeSize; i++){
            map[edge[i][0]].add(edge[i][1]);
            map[edge[i][1]].add(edge[i][0]);
        }
        
        Queue<Integer> queue = new LinkedList<>();
        queue.offer(1);
        boolean[] visited = new boolean[n+1];
        visited[1] = true;
        while(!queue.isEmpty()){
            int size = queue.size();
            cnt = 0;
            for(int i = 0; i< size; i++){
                int node = queue.poll();
                
                cnt ++;                
                
                for(int next : map[node]){
                    if(!visited[next]){
                        visited[next] = true;
                        queue.offer(next);
                    }
                }                
            }
        }
        
        return cnt;        
    }
}