struct Queue<T> {
var input: [T] = []
var output: [T] = []
var isEmpty: Bool {
return input.isEmpty && output.isEmpty
}
var count: Int {
return input.count + output.count
}
mutating func enqueue(_ element: T) {
input.append(element)
}
mutating func delete() -> T {
if output.isEmpty {
output = input.reversed()
input.removeAll()
}
return output.removeLast()
}
}
let input = readLine()!.split(separator: " ").map{ Int(String($0))! }
let (N, M, K, X) = (input[0], input[1], input[2], input[3])
var graph: [[Int]] = Array(repeating: [], count: N + 1)
var visited = Array(repeating: -1, count: N + 1)
var queue = Queue<Int>()
var answer = ""
for _ in 0..<M {
let input = readLine()!.split(separator: " ").map{ Int(String($0))! }
graph[input[0]].append(input[1])
}
bfs(X)
func bfs(_ city: Int) {
visited[city] = 0
queue.enqueue(city)
while !queue.isEmpty {
let now = queue.delete()
for node in graph[now] {
if visited[node] == -1 {
visited[node] = visited[now] + 1
queue.enqueue(node)
}
}
}
}
for (index, distance) in visited.enumerated() {
if distance == K {
answer += "\(index)\n"
}
}
print(answer == "" ? "-1" : answer)
각 도시의 최단 거리를 구해야 하기 때문에 BFS를 사용한다.