문제 풀이
오늘의 문제 - 백준18352.특정 거리의 도시 찾기
나의 풀이
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
int k = Integer.parseInt(st.nextToken());
int x = Integer.parseInt(st.nextToken());
ArrayList<Integer>[] graph = new ArrayList[n + 1];
for (int i = 1; i <= n; i++) {
graph[i] = new ArrayList<>();
}
for (int i = 0; i < m; i++) {
st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
graph[a].add(b);
}
int[] distance = new int[n + 1];
Arrays.fill(distance, -1);
distance[x] = 0;
Queue<Integer> queue = new LinkedList<>();
queue.add(x);
while (!queue.isEmpty()) {
int current = queue.poll();
for (int next : graph[current]) {
if (distance[next] == -1) {
distance[next] = distance[current] + 1;
queue.add(next);
}
}
}
boolean found = false;
for (int i = 1; i <= n; i++) {
if (distance[i] == k) {
System.out.println(i);
found = true;
}
}
if (!found) {
System.out.println(-1);
}
}
}