문제 링크 (opens new window)

# 풀이

  1. Queue 직접 정의
  2. BFS
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 nm = readLine()!.split(separator: " ").map { Int($0)! }; let n = nm[0]; let m = nm[1]
let dy = [-1, 0, 1, 0]; let dx = [0, 1, 0, -1]
var adj: [[Int]] = .init(repeating: [], count: 104)
var visited: [[Int]] = []

for i in 0..<n {
    adj[i] = readLine()!.map { Int(String($0))! }
    visited.append(.init(repeating: 0, count: adj[i].count))
}

func bfs(_ here: (Int, Int)) {
    var q = Queue<(Int, Int)>()
    visited[here.0][here.1] = 1
    q.enqueue(here)

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

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

            if ny < 0 || nx < 0 || ny >= n || nx >= m || adj[ny][nx] == 0 || visited[ny][nx] != 0 {
                continue
            }
            visited[ny][nx] = visited[here.0][here.1] + 1
            q.enqueue((ny, nx))
        }
    }
}

bfs((0,0))
print(visited[n-1][m-1])