기록하는 개발자

[프로그래머스][코딩테스트 고득점 Kit][java,javascript] 가장 먼 노드 본문

Algorithm

[프로그래머스][코딩테스트 고득점 Kit][java,javascript] 가장 먼 노드

밍맹030 2023. 8. 14. 15:25
728x90

https://school.programmers.co.kr/learn/courses/30/lessons/49189?language=javascript 

 

프로그래머스

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

programmers.co.kr

전체 코드

[ javascript ]

function solution(n, edge) {    
    // 양방향 그래프 생성
    const graph = Array.from(Array(n),()=>[]);
    for(let i=0; i<edge.length; i++){
        graph[edge[i][0]-1].push(edge[i][1]-1);
        graph[edge[i][1]-1].push(edge[i][0]-1);
    }
    
    let visited = Array.from({length : n},()=>0);
    visited[0] = 1;
    let queue = [0];

    while (queue.length!=0) {
        let now = queue.shift();
        for (let next of graph[now]) {
            // 방문한 적 없는 노드인 경우
            if (visited[next] == 0) {
                // 다음 방문 노드 경로 = 현재 노드까지의 경로 + 1
                visited[next] =  visited[now]+1;
                queue.push(next);
            }
        }
    }
    // Math.max(...visited) : 1과 가장 멀리 떨어진 노드의 경로 길이
    return visited.filter(n => n == Math.max(...visited)).length;
}

[java]

import java.util.*;

class Solution {
    public int solution(int n, int[][] edge) {
        ArrayList<Integer>[] graph = new ArrayList[n + 1];
        for (int i = 0; i < n; i++) 
            graph[i] = new ArrayList<>();
		
        for(int[] node : edge) {
            graph[node[0]-1].add(node[1]-1);
            graph[node[1]-1].add(node[0]-1);
        }

        Queue<Integer> queue = new LinkedList<>(); 
        queue.offer(0);
        
        int [] visited = new int[n];
        visited[0]=1;
        
        while(queue.size()!=0){
            int top = queue.poll();
            for (int i : graph[top]) {
                if (visited[i] == 0) {
                    visited[i] =  visited[top]+1;
                    queue.offer(i);
                }
            }
        }
        int max = Arrays.stream(visited).max().getAsInt();
        int answer = 0;
        
        for (int i = 0; i < n; i++){
            if(visited[i]==max) answer++;
        }

        return answer;
    }
}
728x90