Open zekexros opened 3 years ago
why timeout...😥
import Foundation
var memo = Set<Int>()
func bfs(_ target: Int, _ arr: [Int], _ depth: Int) -> Int {
if arr.contains(target) {
return depth
}
var next: [Int] = []
arr.forEach {
if !memo.contains($0 - 1) {
next.append($0 - 1)
}
if !memo.contains($0 + 1) {
next.append($0 + 1)
}
if !memo.contains($0 * 2) {
next.append($0 * 2)
}
memo.insert($0 - 1)
memo.insert($0 + 1)
if $0 * 2 < 100000 { memo.insert($0 * 2) }
}
return bfs(target, next, depth + 1)
}
let input = readLine()!.components(separatedBy: " ")
let start = Int(input[0])!
let end = Int(input[1])!
let ans = bfs(end, [start], 0)
print(ans)
https://www.acmicpc.net/problem/1697