-
Notifications
You must be signed in to change notification settings - Fork 3
/
[프로그래머스] 신재웅_경주로 건설.swift
46 lines (40 loc) · 1.61 KB
/
[프로그래머스] 신재웅_경주로 건설.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import Foundation
var directions: [(Int, Int)] = [(-1, 0), (0, -1), (1, 0), (0, 1)]
var minCost: [[Int?]] = []
func solution(_ board:[[Int]]) -> Int {
let n = board.count
minCost = Array(repeating: Array(repeating: nil, count: n), count: n)
var result: Int = n * n * 600
bruteFource(n: n, pastDirection: (1, 0), from: (0, 0), visited: board, cost: 0, result: &result)
bruteFource(n: n, pastDirection: (0, 1), from: (0, 0), visited: board, cost: 0, result: &result)
return result
}
func bruteFource(n: Int, pastDirection: (Int, Int), from: (Int, Int), visited: [[Int]], cost: Int, result: inout Int) {
guard cost < result else { return }
if let pastMinCost = minCost[from.0][from.1] {
if cost <= pastMinCost + 500 {
minCost[from.0][from.1] = min(pastMinCost, cost)
} else {
return
}
} else {
minCost[from.0][from.1] = cost
}
if from == (n-1, n-1) {
result = min(cost, result)
return
}
for direction in directions {
let to: (Int, Int) = (from.0 + direction.0, from.1 + direction.1)
guard 0..<n ~= to.0, 0..<n ~= to.1,
visited[to.0][to.1] != 1
else { continue }
var futureVisited: [[Int]] = visited
futureVisited[to.0][to.1] = 1
if pastDirection == direction {
bruteFource(n: n, pastDirection: direction, from: to, visited: futureVisited, cost: cost+100, result: &result)
} else {
bruteFource(n: n, pastDirection: direction, from: to, visited: futureVisited, cost: cost+600, result: &result)
}
}
}