- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Minimum Path Sum in C++
Suppose we have a m x n matrix filled with non-negative integers, find a path from top left corner to bottom right corner which minimizes the sum of all numbers along its path. Movements can only be either down or right at any point in time. So for example, if the matrix is like below
1 | 3 | 1 |
1 | 5 | 1 |
4 | 2 | 1 |
The output will be 7, the path will be 1,3,1,1,1, this will minimize the sum
Let us see the steps −
a := number of rows, b := number of columns
i := a – 1, j := b - 1
while j >= 0
matrix[a, j] := matrix[a, j] + matrix[a, j + 1]
decrease j by 1
while i >= 0
matrix[i, b] := matrix[i, b] + matrix[i + 1, b]
decrease i by 1
j := b - 1 and i := row - 1
while i >= 0
while j >= 0
matrix[i, j] := matrix[i, j] + minimum of matrix[i, j + 1] and matrix[i + 1, j]
decrease j by 1
j := b - 1
i := i - 1
return matrix[0, 0]
Example
Let us see the following implementation to get better understanding −
class Solution(object): def minPathSum(self, grid): """ :type grid: List[List[int]] :rtype: int """ row = len(grid)-1 column = len(grid[0])-1 i=row-1 j=column-1 while j>=0: grid[row][j]+=grid[row][j+1] j-=1 while i>=0: grid[i][column]+=grid[i+1][column] i-=1 j=column-1 i = row-1 while i>=0: while j>=0: grid[i][j] += min(grid[i][j+1],grid[i+1][j]) j-=1 j=column-1 i-=1 return(grid[0][0])
Input
[[1,3,1],[1,5,1],[4,2,1]]
Output
7
- Related Articles
- Minimum Falling Path Sum in C++
- Minimum Falling Path Sum II in C++
- Minimum Sum Path in a Triangle in C++
- Minimum Path Sum in Python
- Minimum Sum Path In 3-D Array in C++
- Minimum sum falling path in a NxN grid in C++
- Minimum sum path between two leaves of a binary trees in C++
- Path Sum III in C++
- Path Sum IV in C++
- C Program for Minimum Cost Path
- Maximum path sum in matrix in C++
- Minimum number of stops from given path in C++
- Maximum Sum Path in Two Arrays in C++
- Maximum path sum in a triangle in C++
- Minimum Size Subarray Sum in C++
