1 ๋ถ„ ์†Œ์š”

๐Ÿ“ [D4_1238] Contact

import java.io.IOException;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
import java.util.StringTokenizer;

public class Solution{
    static StringTokenizer st;
    static int N;
    static int[][] arr;
    static int[] visited;
    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);
        StringBuilder sb = new StringBuilder();

        for(int tc=1; tc<=10; tc++){
            sb.append("#").append(tc).append(" ");

            // ๋ฐ์ดํ„ฐ ๊ธธ์ด
            N = sc.nextInt();

            // ์‹œ์ž‘์ 
            int first = sc.nextInt();

            // ๊ฐ„์„  ์ •๋ณด ์ €์žฅ ๋ฐฐ์—ด
            arr = new int[101][101];

            // ์—ฐ๋ฝ ๋ฐ›์€ ์œ ๋ฌด
            visited = new int[101];

            for(int i =0; i<N/2; i++){
                // ๋ฐฉํ–ฅ์„ฑ์ด ์žˆ๋‹ค
                arr[sc.nextInt()][sc.nextInt()] = 1;
            }

            bfs(first);

          // ์ตœ๋Œ“๊ฐ’ ๊ตฌํ•˜๊ธฐ
            int maxCnt = Integer.MIN_VALUE;
            int maxIdx = Integer.MIN_VALUE;
            for(int i=1; i<101; i++){
                // ๊ฐ€์ง€์น˜๊ธฐ
                if(visited[i]==0){
                    continue;
                }
                // ์ œ์ผ ๋งŽ์€ cnt๊ตฌํ•˜๊ธฐ
               maxCnt = Math.max(visited[i], maxCnt);
                if(maxCnt == visited[i]){
                    maxIdx = Math.max(maxIdx, i);
                }
            }

            sb.append(maxIdx).append("\n");
        }
        System.out.println(sb);
    }

    public static void bfs(int start){

        Queue<Integer> queue = new LinkedList<Integer>();

        queue.offer(start);
        visited[start] = 1;

        while(!queue.isEmpty()){
            int current = queue.poll();

            for(int i=1; i<101; i++) {
                if (visited[i]==0 && arr[current][i] != 0) {
                        queue.offer(i);
                        visited[i] = visited[current]+1;
                }
            }
        }
    }
}

๐Ÿค” ๋‚˜์˜ ์ƒ๊ฐ

์ผ๋ฐ˜์ ์œผ๋กœ boolean์œผ๋กœ bfs()์—์„œ ๋ฐฉ๋ฌธ ์œ ๋ฌด๋ฅผ ๊ตฌํ•˜๋Š”๋ฐ ์ด ๋ฌธ์ œ์—์„œ๋Š” intํ˜• ๋ฐฐ์—ด๋กœ ๋ช‡๋ฒˆ ๋งŒ์— ์—ฐ๊ฒฐ์ด ๋˜์—ˆ๋Š”์ง€ ์ฒดํฌ๋ฅผ ํ•ด์ฃผ์—ˆ๋‹ค.
๊ทธ๋ž˜์„œ ๊ทธ ๊ฐ’์„ ์ด์šฉํ•ด ๊ฐ™์€ ์ˆ˜ ๋ผ๋ฆฌ์—์„œ๋„ ์ตœ๋Œ“๊ฐ’์„ ๊ตฌํ•ด์ฃผ์—ˆ๋‹ค.
Queue๋ฅผ ์ด์šฉํ•ด์„œ bfs๋ฅผ ๊ตฌํ˜„ํ•ด์ฃผ๊ณ  visited ๋ฐฐ์—ด์„ ๋Œ๋ฉฐ ๊ฐ€์žฅ ๋’ค์— ์—ฐ๋ฝ์„ ๋ฐ›์€ ์‚ฌ๋žŒ ์ค‘์— ๊ฐ€์žฅ ํฐ ์ˆ˜๋ฅผ ๊ตฌํ•ด์ฃผ์—ˆ๋‹ค.
visited ๋ฐฐ์—ด๋กœ ์นด์šดํŒ… ํ•ด์ค€๋‹ค๋ฉด ์–ด๋ ต์ง€ ์•Š์€ ๋ฌธ์ œ์˜€๋‹ค.
๋‚˜๋Š” static์œผ๋กœ ๋ฐฐ์—ด์„ ์„ ์–ธ ํ•ด๋†“๊ณ  ์•ˆ์—์„œ ์ง€์—ญ์œผ๋กœ ๋‹ค์‹œ ์„ ์–ธ์„ ํ•ด์„œ ๊ฐ’์ด ์ด์ƒํ•œ ์˜ค๋ฅ˜๋ฅผ ๋นจ๋ฆฌ ์ฐพ์ง€ ๋ชปํ•ด ๊ณ ์ƒํ•˜์˜€๋”ฐ..ใ