on
[프로그래머스] 가장 먼 노드
[프로그래머스] 가장 먼 노드
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
package com.example.study.algorithm.programmers; import java.util. * ; class 가장먼노드 { boolean check[]; int distance[]; List < Integer > [] list; public int solution( int n, int [][] edge) { int answer = 0 ; list = new ArrayList[n]; for ( int i = 0 ; i < n; i + + ) { list[i] = new ArrayList < > (); } for ( int i[] : edge) { list[i[ 0 ] - 1 ]. add (i[ 1 ] - 1 ); list[i[ 1 ] - 1 ]. add (i[ 0 ] - 1 ); } check = new boolean [n]; distance = new int [n]; Queue < Integer > q = new LinkedList < > (); q. add ( 0 ); check[ 0 ] = true ; while ( ! q.isEmpty()) { int temp = q.poll(); for ( int a : list[temp]) { if (check[a] = = false ) { check[a] = true ; distance[a] = distance[temp] + 1 ; q. add (a); } } } int max = 0 ; for ( int i : distance) { if (i > max) { max = i; } } for ( int i : distance) { if (max = = i) { answer + + ; } } return answer; } } Colored by Color Scripter
from http://algorithm-master.tistory.com/140 by ccl(A) rewrite - 2021-09-12 19:00:53