From c7c4cfb562ee54d04b4ba62e4e0bf888f023a22c Mon Sep 17 00:00:00 2001 From: songyc macbook Date: Thu, 11 Sep 2025 20:54:09 +0900 Subject: [PATCH] 20250911 baekjoon --- code_study/Baekjoon/swift/13549.swift | 64 +++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 code_study/Baekjoon/swift/13549.swift diff --git a/code_study/Baekjoon/swift/13549.swift b/code_study/Baekjoon/swift/13549.swift new file mode 100644 index 0000000..d0bc3fb --- /dev/null +++ b/code_study/Baekjoon/swift/13549.swift @@ -0,0 +1,64 @@ +struct Queue { + var enqueue: [Int] = [] + var dequeue: [Int] = [] + + func isEmpty() -> Bool { + return enqueue.isEmpty && dequeue.isEmpty + } + + mutating func push(_ element: Int) { + enqueue.append(element) + } + + mutating func pushFirst(_ element: Int) { + dequeue.append(element) + } + + mutating func pop() -> Int? { + if dequeue.isEmpty { + dequeue = enqueue.reversed() + enqueue.removeAll() + } + return dequeue.popLast() + } +} + +if let NM = readLine()?.split(separator: " ").compactMap({Int($0)}), + let N = NM.first, let M = NM.last +{ + let maxAxis = 100000 + var qu: Queue = Queue() + var visited: [Int] = Array(repeating: -1, count: maxAxis + 1) + qu.push(N) + visited[N] = 0 + + while !qu.isEmpty() { + if let current: Int = qu.pop() { + if current == M { + print(visited[current]) + break + } + + let nextAxis: [Int] = [current*2, current+1, current-1] + + for i in 0...2 { + let next: Int = nextAxis[i] + + if 0 <= next && next <= maxAxis { + if i==0 { + if visited[next] == -1 || visited[next] > visited[current] { + qu.pushFirst(next) + visited[next] = visited[current] + } + } + else { + if visited[next] == -1 || visited[next] > visited[current] + 1 { + qu.push(next) + visited[next] = visited[current] + 1 + } + } + } + } + } + } +}