Skip to content

Commit

Permalink
1
Browse files Browse the repository at this point in the history
  • Loading branch information
isaiahliu committed Dec 25, 2024
1 parent 977a905 commit 661ee93
Showing 1 changed file with 25 additions and 21 deletions.
46 changes: 25 additions & 21 deletions src/main/kotlin/p32xx/Problem3218.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,39 +5,43 @@ import util.expect
fun main() {
class Solution {
fun minimumCost(m: Int, n: Int, horizontalCut: IntArray, verticalCut: IntArray): Int {
val cache = hashMapOf<Pair<Pair<Int, Int>, Pair<Int, Int>>, Int>()

fun dfs(hStart: Int, hEnd: Int, vStart: Int, vEnd: Int): Int {
val cacheKey = (hStart to hEnd) to (vStart to vEnd)
val cache = Array(m) {
Array(m) { mSize ->
Array(n) {
IntArray(n) { nSize ->
0 - (mSize + nSize)
}
}
}
}

return when {
hStart > hEnd && vStart > vEnd -> 0
cacheKey in cache -> cache[cacheKey] ?: 0
else -> {
var min = Int.MAX_VALUE
fun dfs(hRange: IntRange, vRange: IntRange): Int {
if (cache[hRange.first][hRange.last - hRange.first + 1][vRange.first][vRange.last - vRange.first + 1] < 0) {
var min = Int.MAX_VALUE

(hStart..hEnd).forEach {
min = minOf(min, horizontalCut[it] + dfs(hStart, it - 1, vStart, vEnd) + dfs(it + 1, hEnd, vStart, vEnd))
}
(vStart..vEnd).forEach {
min = minOf(min, verticalCut[it] + dfs(hStart, hEnd, vStart, it - 1) + dfs(hStart, hEnd, it + 1, vEnd))
}
hRange.forEach {
min = minOf(min, horizontalCut[it] + dfs(hRange.first until it, vRange) + dfs(it + 1..hRange.last, vRange))
}

cache[cacheKey] = min
min
vRange.forEach {
min = minOf(min, verticalCut[it] + dfs(hRange, vRange.first until it) + dfs(hRange, it + 1..vRange.last))
}

cache[hRange.first][hRange.last - hRange.first + 1][vRange.first][vRange.last - vRange.first + 1] = min
}

return cache[hRange.first][hRange.last - hRange.first + 1][vRange.first][vRange.last - vRange.first + 1]
}

return dfs(0, horizontalCut.lastIndex, 0, verticalCut.lastIndex)
return dfs(horizontalCut.indices, verticalCut.indices)
}
}

expect {
Solution().minimumCost(
4, 5,
intArrayOf(0, 3),
intArrayOf(0, 2),
3, 2,
intArrayOf(1, 3),
intArrayOf(5),
)
}
// expect {
Expand Down

0 comments on commit 661ee93

Please sign in to comment.