| 
 | 1 | +"""  | 
 | 2 | +Problem Link: https://practice.geeksforgeeks.org/problems/path-in-matrix3805/1  | 
 | 3 | + | 
 | 4 | +Given a NxN matrix of positive integers. There are only three possible moves from a cell Matrix[r][c].  | 
 | 5 | +Matrix [r+1] [c]  | 
 | 6 | +Matrix [r+1] [c-1]  | 
 | 7 | +Matrix [r+1] [c+1]  | 
 | 8 | +Starting from any column in row 0, return the largest sum of any of the paths up to row N-1.  | 
 | 9 | + | 
 | 10 | +Example 1:  | 
 | 11 | +Input: N = 2  | 
 | 12 | +Matrix = {{348, 391},  | 
 | 13 | + {618, 193}}  | 
 | 14 | +Output: 1009  | 
 | 15 | +Explaination: The best path is 391 -> 618.   | 
 | 16 | +It gives the sum = 1009.  | 
 | 17 | + | 
 | 18 | +Example 2:  | 
 | 19 | +Input: N = 2  | 
 | 20 | +Matrix = {{2, 2},  | 
 | 21 | + {2, 2}}  | 
 | 22 | +Output: 4  | 
 | 23 | +Explaination: No matter which path is   | 
 | 24 | +chosen, the output is 4.  | 
 | 25 | + | 
 | 26 | +Your Task:  | 
 | 27 | +You do not need to read input or print anything. Your task is to complete the function maximumPath() which takes the size N   | 
 | 28 | +and the Matrix as input parameters and returns the highest maximum path sum.  | 
 | 29 | + | 
 | 30 | +Expected Time Complexity: O(N*N)  | 
 | 31 | +Expected Auxiliary Space: O(N*N)  | 
 | 32 | + | 
 | 33 | +Constraints:  | 
 | 34 | +1 ≤ N ≤ 100  | 
 | 35 | +1 ≤ Matrix[i][j] ≤ 1000  | 
 | 36 | +"""  | 
 | 37 | +class Solution:  | 
 | 38 | + def maximumPath(self, N, Matrix):  | 
 | 39 | + dp = [[0] * N for _ in range(N)]  | 
 | 40 | + | 
 | 41 | + directions = [[1, 1], [1, -1], [1, 0]]  | 
 | 42 | + | 
 | 43 | + max_path_sum = 0  | 
 | 44 | + | 
 | 45 | + for row in range(N-1, -1, -1):  | 
 | 46 | + for col in range(N):  | 
 | 47 | + max_val = 0  | 
 | 48 | + for r, c in directions:  | 
 | 49 | + new_row = r + row  | 
 | 50 | + new_col = c + col   | 
 | 51 | + if new_row >= 0 and new_col >= 0 and new_row < N and new_col < N:  | 
 | 52 | + max_val = max(max_val, dp[new_row][new_col])  | 
 | 53 | + | 
 | 54 | + dp[row][col] = Matrix[row][col] + max_val  | 
 | 55 | + max_path_sum = max(max_path_sum, dp[row][col])  | 
 | 56 | + | 
 | 57 | + return max_path_sum  | 
0 commit comments