문제 링크 (opens new window)

# 문제설명

  1. 최단거리 문제 - BFS
  2. 좌표 변화량 제대로 체크할것
import Foundation

struct Queue<T> {
    var array: [T?] = []
    var head = 0

    var isEmpty: Bool {
        return count == 0
    }

    var count: Int {
        return array.count - head
    }

    mutating func enqueue(_ element: T) {
        array.append(element)
    }

    mutating func dequeue() -> T? {
        guard head < array.count,
              let element = array[head] else { return nil }

        array[head] = nil
        head += 1

        let percentage = Double(head) / Double(array.count)
        if percentage > 0.25 && array.count > 50 {
            array.removeFirst(head)
            head = 0
        }

        return element
    }

    var front: T? {
        if isEmpty {
            return nil
        } else {
            return array[head]
        }
    }
}

let T = Int(readLine()!)!
let dy = [-2, -2, -1, 1, 2, 2, 1, -1]; let dx = [-1, 1, 2, 2, 1, -1, -2, -2]

for _ in 0..<T {
    let I = Int(readLine()!)!
    let start = readLine()!.split(separator: " ").map { Int($0)! }
    let dest = readLine()!.split(separator: " ").map { Int($0)! }

    if start[0] == dest[0] && start[1] == dest[1] {
        print(0)
        continue
    }

    var adj: [[Int]] = .init(repeating: .init(repeating: 0, count: I), count: I)
    var q = Queue<(Int, Int)>()
    q.enqueue((start[0], start[1]))

    while !q.isEmpty {
        guard let here = q.dequeue() else { break }

        for i in 0..<8 {
            let ny = dy[i] + here.0
            let nx = dx[i] + here.1

            if ny < 0 || nx < 0 || ny >= I || nx >= I || adj[ny][nx] != 0 { continue }

            adj[ny][nx] = adj[here.0][here.1] + 1
            q.enqueue((ny, nx))
        }
    }

    print(adj[dest[0]][dest[1]])
}