题目:
leetcode.cn/problems/mi…
算法:
方法一:模拟
仔细分析题意发现,先移动行方向,还是先移动列方向,到达指定为止的cost都是相同的,也就是说从开始位置移动到home位置只有一个总cost,我们计算cost就行
func minCost(startPos []int, homePos []int, rowCosts []int, colCosts []int) int {
ans := 0
rowFinished, colFinished := false, false
rowDelta, colDelta := 1, 1
if startPos[0] > homePos[0] {
rowDelta = -1
}
if startPos[1] > homePos[1] {
colDelta = -1
}
if startPos[0] != homePos[0] {
for i := startPos[0] + rowDelta; !rowFinished && i < len(rowCosts); i = i + rowDelta {
ans = ans + rowCosts[i]
if i == homePos[0] {
rowFinished = true
}
}
}
if startPos[1] != homePos[1] {
for j := startPos[1] + colDelta; !colFinished && j < len(colCosts); j = j + colDelta {
ans = ans + colCosts[j]
if j == homePos[1] {
colFinished = true
}
}
}
return ans
}
优化方法一:
代码写的太复杂了,优化一下:
func minCost(startPos []int, homePos []int, rowCosts []int, colCosts []int) int {
ans := 0
for i := min(startPos[0], homePos[0]); i <= max(startPos[0], homePos[0]); i ++ {
ans = ans + rowCosts[i]
}
for j := min(startPos[1], homePos[1]); j <= max(startPos[1], homePos[1]); j ++ {
ans = ans + colCosts[j]
}
// 减去起始位置的cost
ans = ans - rowCosts[startPos[0]] - colCosts[startPos[1]]
return ans
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func max(a, b int) int {
if a > b {
return a
}
return b
}