iOS 개발 공부

[Swift] 7672번 : 나이트의 이동 본문

코딩테스트/백준

[Swift] 7672번 : 나이트의 이동

물복딱복준복 2024. 3. 18. 17:56

https://www.acmicpc.net/problem/7562

 

7562번: 나이트의 이동

체스판 위에 한 나이트가 놓여져 있다. 나이트가 한 번에 이동할 수 있는 칸은 아래 그림에 나와있다. 나이트가 이동하려고 하는 칸이 주어진다. 나이트는 몇 번 움직이면 이 칸으로 이동할 수

www.acmicpc.net

import Foundation

typealias Position = (x: Int, y: Int)


func +(lhs: Position, rhs: Position) -> Position {
    Position(lhs.x + rhs.x, lhs.y + rhs.y)
}


func solution() {
    
    let repetition = Int(readLine()!)!

    for _ in 1...repetition {
        
        let dimension = Int(readLine()!)!
        
        
        let startPositionArray = readLine()!
            .components(separatedBy: " ")
            .compactMap { Int($0) }
            
        let startPosition = Position(startPositionArray.first!, startPositionArray.last!)
        
        
        let targetPositionArray = readLine()!
            .components(separatedBy: " ")
            .compactMap { Int($0) }
        
        let targetPosition = Position(targetPositionArray.first!, targetPositionArray.last!)
        
        print(bfs(dimension, startPosition, targetPosition))
    }

    
}


func bfs( _ dimension: Int, _ start: Position, _ target: Position) -> Int {
    
    let dirs: [Position] = [(2,1), (1,2),(-1,2),(-2,1), (-2, -1), (-1,-2), (1,-2),( 2,-1)]
    
    
    var index = 0
    var queue: [Position] = [start]
    var chessBoard = Array(repeating: Array(repeating: 0, count: dimension), count: dimension)
    
    
    while index < queue.count {
        
        let currentPosition = queue[index]
        index += 1
        
        if currentPosition == target {
            return chessBoard[target.x][target.y]
        }
        
        for dir in dirs {
            let nextPosition = currentPosition + dir
            
            if nextPosition.x < 0 || nextPosition.x >= dimension ||
                nextPosition.y < 0 || nextPosition.y >= dimension ||
                chessBoard[nextPosition.x][nextPosition.y] > 0 { continue }
            
            
            chessBoard[nextPosition.x][nextPosition.y] = chessBoard[currentPosition.x][currentPosition.y] + 1
            queue.append(nextPosition)
        }
    }
    
    return chessBoard[target.x][target.y]
    
}


solution()

 

'코딩테스트 > 백준' 카테고리의 다른 글

[Swift] 2667번 : 단지번호 붙이기  (0) 2024.03.18
[Swift] 2583번 : 영역 구하기  (0) 2024.03.18
[Swift] 1012번 : 유기농 배추  (0) 2024.03.18
[Swift] 1697번 : 숨바꼭질  (0) 2024.03.18
[Swift] 2178번 : 미로탐색  (0) 2024.02.05