Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save knowsudhanshu/162981714061fd0d9a07ef881773be51 to your computer and use it in GitHub Desktop.
Save knowsudhanshu/162981714061fd0d9a07ef881773be51 to your computer and use it in GitHub Desktop.
Min cost path in Matrix
let input = [
[1,3,5,8],
[4,2,1,7],
[4,3,2,3]
]
func minPathCost(input: [[Int]], m: Int, n: Int) -> Int {
if m == 0 && n == 0 {
return input[0][0]
}
if m == 0 {
return minPathCost(input: input, m: m, n: n-1) + input[m][n]
}
if n == 0 {
return minPathCost(input: input, m: m-1,n: n) + input[m][n]
}
let x = minPathCost(input: input, m: m-1,n: n)
let y = minPathCost(input: input, m: m, n: n-1)
return min(x,y) + input[m][n]
}
let result = minPathCost(input: input, m: 2, n: 3)
print(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment