Last active
May 1, 2024 15:56
-
-
Save knowsudhanshu/895637a6fb38f41a39a722af58939977 to your computer and use it in GitHub Desktop.
Max cost path 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] | |
] | |
/* | |
// Recursion | |
func maxPathCost(input: [[Int]], m: Int, n: Int) -> Int { | |
if m == 0 && n == 0 { | |
return input[0][0] | |
} | |
if m == 0 { | |
return maxPathCost(input: input, m: m, n: n-1) + input[m][n] | |
} | |
if n == 0 { | |
return maxPathCost(input: input, m: m-1,n: n) + input[m][n] | |
} | |
let x = maxPathCost(input: input, m: m-1,n: n) | |
let y = maxPathCost(input: input, m: m, n: n-1) | |
return max(x,y) + input[m][n] | |
} | |
*/ | |
/* | |
// Memoaized solution | |
var memo: [[Int]] = [[-1, -1, -1, -1], | |
[-1, -1, -1, -1], | |
[-1, -1, -1, -1] | |
] | |
func maxPathCost(input: [[Int]], m: Int, n: Int) -> Int { | |
if memo[m][n] != -1 { | |
return memo[m][n] | |
} | |
if m == 0 && n == 0 { | |
memo[m][n] = input[0][0] | |
} | |
else if m == 0 { | |
memo[m][n] = maxPathCost(input: input, m: m, n: n-1) + input[m][n] | |
} | |
else if n == 0 { | |
memo[m][n] = maxPathCost(input: input, m: m-1,n: n) + input[m][n] | |
} else { | |
let x = maxPathCost(input: input, m: m-1,n: n) | |
let y = maxPathCost(input: input, m: m, n: n-1) | |
memo[m][n] = max(x,y) + input[m][n] | |
} | |
return memo[m][n] | |
} | |
*/ | |
/* | |
// DP - Bottom Up | |
//// DP - BottomUp approach | |
var memo: [[Int]] = [[-1, -1, -1, -1], | |
[-1, -1, -1, -1], | |
[-1, -1, -1, -1] | |
] | |
func maxPathCost(input: [[Int]], m: Int, n: Int) -> Int { | |
memo[0][0] = input[0][0] | |
// Top row | |
for column in 1..<input[0].count { | |
memo[0][column] = memo[0][column - 1] + input[0][column] | |
} | |
// Left column | |
for row in 1..<input.count { | |
memo[row][0] = memo[row - 1][0] + input[row][0] | |
} | |
// Filling other cells | |
for row in 1..<input.count { | |
for column in 1..<input[0].count { | |
memo[row][column] = max(memo[row - 1][column], memo[row][column - 1]) + input[row][column] | |
} | |
} | |
return memo[m][n] | |
} | |
*/ | |
let result = maxPathCost(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