Skip to content

Commit

Permalink
Refactor solution to Minimum Path Sum
Browse files Browse the repository at this point in the history
  • Loading branch information
soapyigu committed Oct 3, 2022
1 parent 8dc4b64 commit f6c0b05
Showing 1 changed file with 8 additions and 12 deletions.
20 changes: 8 additions & 12 deletions DP/MinimumPathSum.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,27 +6,23 @@

class MinimumPathSum {
func minPathSum(_ grid: [[Int]]) -> Int {
guard grid.count != 0 && grid[0].count != 0 else{
return 0
}

let m = grid.count, n = grid[0].count
var dp = Array(repeating: Array(repeating: 0, count: n), count: m)
var dp = grid

for i in 0..<m {
for j in 0..<n {
if i == 0 && j == 0{
if i == 0 && j == 0 {
dp[i][j] = grid[i][j]
} else if i == 0 {
dp[i][j] = dp[i][j - 1] + grid[i][j]
dp[i][j] += dp[i][j - 1]
} else if j == 0 {
dp[i][j] = dp[i - 1][j] + grid[i][j]
dp[i][j] += dp[i - 1][j]
} else {
dp[i][j] = min(dp[i][j - 1], dp[i - 1][j]) + grid[i][j]
dp[i][j] += min(dp[i - 1][j], dp[i][j - 1])
}
}
}

return dp[m - 1][n - 1]
}
}
}

0 comments on commit f6c0b05

Please sign in to comment.