๋ฐ์ํ
import Foundation
/// 1: ์ด๋๊ฐ๋ฅ, 0: ์ด๋๋ถ๊ฐ๋ฅ
/// (1, 1)์์ (N, M)์ ์์น๋ก ์ด๋ํ๋ ์ต๋จ๊ฑฐ๋ฆฌ ๊ตฌํด๋ผ
/// dfs ์๊ณ ๋ฆฌ์ฆ ํน์ฑ ์ ์ต๋จ๊ฑฐ๋ฆฌ๋ฅผ ์ฐพ์ผ๋ ค๋ฉด ์์ ํ์์ ํ๊ณ ๊ฐ์ฅ ์์ ๊ฐ์ ์ ํํด์ผ ํ๋๋ฐ
/// ๊ฒฝ๋ก๊ฐ ์์ฃผ ๋ง์ ์๋ ์์ผ๋ฏ๋ก ์๊ฐ๋ณต์ก๋๊ฐ ๋งค์ฐ ์ปค์ง๋ค.
/// ๊ทธ๋์ bfs๋ก ํ์ด์ผํ๋ค.
let NM = readLine()!.components(separatedBy: " ").map { Int($0)! }
let N = NM[0]
let M = NM[1]
let dx = [0, 0, -1, 1]
let dy = [-1, 1, 0, 0] // ์ํ์ข์ฐ
// 0๊ณผ 1์ ์ ๋ณด๊ฐ ๋ด๊ธด ๋ณด๋
var board = [[Int]]()
// ๋ฐฉ๋ฌธํ ์ขํ๋ฅผ ๋ด์ ๋ฐฐ์ด
var visited = [[Bool]](repeating: [Bool](repeating: false, count: M), count: N)
// ๊ฒฝ๋ก๋ฅผ ๋ด์ ๊ฑฐ๋ฆฌ๋ฅผ ๋ด์ ๋ฐฐ์ด
var distance = [[Int]](repeating: [Int](repeating: 0, count: M), count: N)
for _ in 0..<N {
let nums = readLine()!.map { Int(String($0))! }
board.append(nums)
}
func bfs() {
distance[0][0] = 1
visited[0][0] = true
var queue: [[Int]] = [[0, 0]]
while !queue.isEmpty {
let pop = queue.removeFirst()
let x = pop[0]
let y = pop[1]
// ์ขํ๋ฅผ ๋๋ฉด์ ๊ฑฐ๋ฆฌ ๋ํด์ฃผ๊ธฐ
for i in 0..<4 {
let nx = x + dx[i]
let ny = y + dy[i]
if nx>=0, nx<N, ny>=0, ny<M {
if !visited[nx][ny], board[nx][ny] == 1 {
distance[nx][ny] = distance[x][y] + 1
visited[nx][ny] = true
queue.append([nx, ny])
}
}
}
}
}
bfs()
print(distance[N-1][M-1])
๋ฐ์ํ
'๐ ์ฝํ > BOJ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Swift] ๋ฐฑ์ค 10026 ์ ๋ก์์ฝ (0) | 2023.04.14 |
---|---|
[Swift] ๋ฐฑ์ค 11399 ATM (0) | 2023.04.12 |
[Swift] ๋ฐฑ์ค2606 ๋ฐ์ด๋ฌ์ค (0) | 2023.04.12 |
[Swift] ๋ฐฑ์ค 1927 ์ต์ ํ (0) | 2023.04.11 |
[Swift] ๋ฐฑ์ค 1074 Z (0) | 2023.04.11 |