20250911 baekjoon
This commit is contained in:
parent
8e2fcb241d
commit
c7c4cfb562
64
code_study/Baekjoon/swift/13549.swift
Normal file
64
code_study/Baekjoon/swift/13549.swift
Normal file
@ -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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
x
Reference in New Issue
Block a user