Given two number N and M. The task is to find the number of shortest paths to reach the cell(i, j) in the grid of size N × M when the moves started from the bottom-left corner
Note: cell(i, j) represents the ith row and jth column in the grid
Input : N = 3, M = 4 Output : 1 3 6 10 1 2 3 4 1 1 1 1 Input : N = 5, M = 2 Output : 1 5 1 4 1 3 1 2 1 1
Approach : An efficient approach is to compute the grid starting from the bottom-left corner.
- The number of shortest paths to reach cell(n, i) is 1, where, 1 < = i < = M
- The number of shortest paths to reach cell(i, 1) is 1, where, 1 < = i < = N
- The number of shortest paths to reach cell(i, j) are the sum the number of shortest paths of cell(i-1, j) and (i, j+1), where, 1 < = j < = M and 1 < = i < = N
Below is the implementation of the above approach :
1 5 1 4 1 3 1 2 1 1
Time complexity: O(N × M)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Check if a path exists for a cell valued 1 to reach the bottom right corner of a Matrix before any cell valued 2
- Sum of cost of all paths to reach a given cell in a Matrix
- Unique paths covering every non-obstacle block exactly once in a grid
- Minimum cells traversed to reach corner where every cell represents jumps
- Number of shortest paths in an unweighted and directed graph
- Check if cells numbered 1 to K in a grid can be connected after removal of atmost one blocked cell
- Maximum path sum that starting with any cell of 0-th row and ending with any cell of (N-1)-th row
- Maximum of all distances to the nearest 1 cell from any 0 cell in a Binary matrix
- Minimum moves taken to move coin of each cell to any one cell of Matrix
- Unique paths in a Grid with Obstacles
- Minimum steps to convert all paths in matrix from top left to bottom right as palindromic paths | Set 2
- Minimum steps to convert all paths in matrix from top left to bottom right as palindromic paths
- Shortest distance between two cells in a matrix or grid
- Johnson's algorithm for All-pairs shortest paths
- Printing Paths in Dijkstra's Shortest Path Algorithm
- Shortest paths from all vertices to a destination
- Check if given path between two nodes of a graph represents a shortest paths
- Minimize flips required to make all shortest paths from top-left to bottom-right of a binary matrix equal to S
- Minimum cells required to reach destination with jumps equal to cell values
- Counts paths from a point to reach Origin
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.