Skip to content

Fixes#4796 MinimumPathSum.py #4908

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions data_structures/MinimumPathSum.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@


def findPath( arr , rows, cols):
#iterating the whole grid

"""
since only two movements are allowed right and down. To arrive at a particular cell
we can either comes from left cell(by taking right step) or
from top cell (by taking down step)
"""
for r in range(rows):
for c in range(cols):
option1, option2 =None, None

#option1 is when minimum path sum to arr[r][c] comes from left
if(c-1>=0):
option1= arr[r][c-1]
#option2 is when minimum path sum to arr[r][c] comes from top
if(r-1>=0):
option2= arr[r-1][c]

if(option1==None and option1==None):
continue
if(option1!=None and option2!=None):
arr[r][c]= min(option1, option2) +arr[r][c]
elif(option1!= None):
arr[r][c]= option1+ arr[r][c]
else:
arr[r][c]= option2+ arr[r][c]

return(arr[rows-1][cols-1])

#defining the grid matrix
grid= [[1,3,1],[1,5,1],[4,2,1]]
#number of rows
rows=len(grid)
#number of columns
cols=len(grid[0])

if(rows==0 or cols==0):
print("please give a valid input")
else:
print( findPath( grid, rows, cols));


"""
Time complexity for this algorithm is O(n^2) , since we are traversing the grid.
Space complexity is O(1), since we are not using any extra space.
"""