Created
May 1, 2024 14:54
-
-
Save knowsudhanshu/162981714061fd0d9a07ef881773be51 to your computer and use it in GitHub Desktop.
Min cost path in Matrix
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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