본문 바로가기
알고리즘

[Swift] 백준 - 미로 탐색

by 고고 2022. 1. 12.

백준 링크 : https://www.acmicpc.net/problem/2178

 

2178번: 미로 탐색

첫째 줄에 두 정수 N, M(2 ≤ N, M ≤ 100)이 주어진다. 다음 N개의 줄에는 M개의 정수로 미로가 주어진다. 각각의 수들은 붙어서 입력으로 주어진다.

www.acmicpc.net

 

import Foundation

let nmArray = readLine()!.split(separator: " ").map { Int($0)! }
let N = nmArray[0]
let M = nmArray[1]

// 1. 그래프 세팅
var graph: [[Int]] = Array(repeating: [Int](), count: N) // [] [1, 2] ...

for i in 0...N - 1 {
    let array = Array(readLine()!).map { Int(String($0))! }
    
    for j in array {
        graph[i].append(j)
    }
}

let dx = [-1, 1, 0, 0]
let dy = [0, 0, -1, 1]


var bfsQueue = [(Int, Int)]()

func bfs(_ x: Int, _ y: Int) {
    bfsQueue.append((x, y))

    while !bfsQueue.isEmpty {
        let node = bfsQueue.removeFirst()
        let x = node.0
        let y = node.1
        
        if x == N && y == M { return }

        for i in 0...3 { // 4가지 방향 확인
            let nx = x + dx[i]
            let ny = y + dy[i]
            
            if nx < 0 || nx >= N || ny < 0 || ny >= M { // 미로 찾기 공간을 벗어난 경우 무시
                continue
            }
            if graph[nx][ny] == 0 { // 벽인 경우 무시
                continue
            }
            if graph[nx][ny] == 1 { // 해당 노드를 처음 방문하는 경우에만 최단 거리 기록
                graph[nx][ny] = graph[x][y] + 1
                bfsQueue.append((nx, ny))
            }
        }
    }
}

bfs(0, 0)

print(graph[N - 1][M - 1])

댓글