Skip to content

Commit 2a64e32

Browse files
committed
boj - 2206 벽 부수고 이동하기
1 parent c261965 commit 2a64e32

1 file changed

Lines changed: 62 additions & 0 deletions

File tree

chanmi/boj/bfs&dfs/boj_2206.swift

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
//
2+
// boj_2206.swift
3+
// algorithm
4+
//
5+
// Created by 황찬미 on 8/5/24.
6+
//
7+
// 벽 부수고 이동하기
8+
// https://www.acmicpc.net/problem/2206
9+
10+
// bfs로 접근해야 하는데 벽을 한개까지는 뿌셔도 됨
11+
// 이게 의미하는것은? -> visited 배열을 3차원으로 접근해서 벽을 뿌셨는지 아닌지를 판단함.
12+
13+
let input = readLine()!.split(separator: " ").map{Int(String($0))!}
14+
let n = input[0]
15+
let m = input[1]
16+
var graph = Array(repeating: Array(repeating: 0, count: m), count: n)
17+
var visited = Array(repeating: Array(repeating: Array(repeating: false, count: m), count: n), count: 2)
18+
19+
for i in 0..<n {
20+
let input = readLine()!.map{Int(String($0))!}
21+
graph[i] = input
22+
}
23+
24+
// 처음 위치
25+
var queue = [(y: 0, x: 0, count: 1, broken: 0)]
26+
27+
// 벽을 안 부순 상태이기 때문에 0일 때
28+
visited[0][0][0] = true
29+
var index = 0
30+
31+
let dy = [-1, 1, 0, 0]
32+
let dx = [0, 0, -1, 1]
33+
34+
var result = -1
35+
36+
while queue.count > index {
37+
let (nowY, nowX, nowCount, nowBroken) = queue[index]
38+
index += 1
39+
40+
if nowY == n-1 && nowX == m-1 {
41+
result = nowCount
42+
break
43+
}
44+
45+
for i in 0..<4 {
46+
let ny = nowY+dy[i]
47+
let nx = nowX+dx[i]
48+
49+
if 0..<n ~= ny && 0..<m ~= nx && !visited[nowBroken][ny][nx] {
50+
51+
if graph[ny][nx] == 0 {
52+
visited[nowBroken][ny][nx] = true
53+
queue.append((ny, nx, nowCount+1, nowBroken))
54+
} else if graph[ny][nx] == 1 && nowBroken == 0 {
55+
visited[1][ny][nx] = true
56+
queue.append((ny, nx, nowCount+1, 1))
57+
}
58+
}
59+
}
60+
}
61+
62+
print(result)

0 commit comments

Comments
 (0)