[BFS] 송아지 찾기

suojae·2023년 12월 14일

BFS

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
profile
Hi 👋🏻 I'm an iOS Developer who loves to read🤓

0개의 댓글