

BFS는 Depth별 큐 탐색이다!


import Foundation
func solution(s: Int, e: Int) -> Int {
let moves = [1, -1, 5]
var queue = [(s, 0)]
var visited = Set<Int>()
while !queue.isEmpty {
let (currentPosition, jumps) = queue.removeFirst()
if currentPosition == e {
return jumps
}
for move in moves {
let nextPosition = currentPosition + move
if nextPosition >= 1, nextPosition <= 10000, !visited.contains(nextPosition) {
visited.insert(nextPosition)
queue.append((nextPosition, jumps + 1))
}
}
}
return -1
}
// Example usage
let result = solution(s: 5, e: 14)
print(result) //3