• Home
  • About
    • Ryureka Moment photo

      Ryureka

      Sin Prisa, Sin Pausa

    • About Me
    • Facebook
    • Github
    • Youtube
  • Projects
  • Posts
    • Posts
    • ProblemSolvings
    • Tags
    • Blog
    • Examples
  • ProblemSolving
    • ProblemSolving
    • BOJ
    • Programmers
    • SWEA
    • LeetCode
  • FrontEnd
    • FrontEnd
    • HTML
  • BackEnd
    • BackEnd
    • Server
      • Server
      • Spring
      • NodeJS
    • DataBase
      • DataBase
      • MySQL
      • MongoDB
  • Programming
    • Programming
    • Java
    • JS
    • Python
    • CleanCode
  • ComputerScience
    • DataStructure
    • Algorithm

[BOJ] 18352. 특정 거리의 도시 찾기

16 Apr 2026

Reading time ~1 minute

  • BFS 풀이

BFS 풀이

단방향 그래프에서 BFS를 이용하여 최단 거리를 구한 후 특정 거리의 도시를 찾아서 출력한다.

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class Main {
	static int N, M, K, X;
	static ArrayList<Integer>[] edge;
	static boolean[] check;
	static int[] dist;
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		N = sc.nextInt();
		M = sc.nextInt();
		K = sc.nextInt();
		X = sc.nextInt();
		
		edge = new ArrayList[N+1];
		check = new boolean[N+1];
		dist = new int[N+1];
		
		for(int i = 1; i <= N; i++) {
			edge[i] = new ArrayList<>();
		}
		
		for(int i = 0; i < M; i++) {
			int v1 = sc.nextInt();
			int v2 = sc.nextInt();
			edge[v1].add(v2);
		}
		
		Queue<Integer> q = new LinkedList<>();
		q.add(X);
		check[X] = true;
		while(!q.isEmpty()) {
			int now = q.poll();
			for(int i = 0; i < edge[now].size(); i++) {
				int next = edge[now].get(i);
				if(!check[next]) {
					dist[next] = dist[now] + 1;
					check[next] = true;
					q.add(next);
				}
			}
		}
		
		ArrayList<Integer> ans = new ArrayList<>();
		for(int i = 1; i <= N; i++) {
			if(dist[i] == K) {
				ans.add(i);
			}
		}
		
		for(int i = 0; i < ans.size(); i++) {
			System.out.println(ans.get(i));
		}
		
		if(ans.size() == 0) System.out.println(-1);
	}	
}


BFS Share