Problem Statement : Find the number of unique paths from source to destination in a grid, given conditions
The idea behind this algorithm is quite simple.
Recursive Algorithm : UniquePaths ( row, column )
C++ Finding all unique paths in a grid using recursion
#include<iostream>
using namespace std;
int Unique_Paths (int row, int col) {
// If the row or column number is less than 0, i.e if we must
// have stepped beyond the grid so there is no path to be found.
if (row < 0 or col < 0)
return 0;
// There is only one path going through the topmost row and leftmost column
if (row == 0 || col == 0) {
return 1;
}
// For all the other cells not in topmost row and leftmost column
// The number of paths is the addtion of paths from the cell above and cell
// to the left of the current cell.
return Unique_Paths (row - 1, col) + Unique_Paths (row, col - 1);
}
int main() {
int rows = 7, cols = 3, paths;
paths = Unique_Paths(rows-1, cols-1);
cout << "Grid Rows : " << rows << " Columns : " << cols << " Paths : " << paths << endl;
rows = 3, cols = 3;
paths = Unique_Paths(rows-1, cols-1);
cout << "Grid Rows : " << rows << " Columns : " << cols << " Paths : " << paths << endl;
return 0;
}
Output
Grid Rows : 7 Columns : 3 Paths : 28
Grid Rows : 3 Columns : 3 Paths : 6
Dynamic Programming Algorithm : UniquePaths ( rows, cols )
Time complexity : O ( m * n ), where m is the number of rows and n is the number of columns in the grid.
C++ program to find all unique paths in a grid using dynamic programming
#include<iostream>
using namespace std;
int UniquePaths (int m, int n) {
int grid[m][n];
cout << "Grid Rows : " << m << ", Columns : " << n << endl;
// All elements of 1'st column = 1
for (int r = 0; r < m ; r++)
grid[r][0] = 1;
// All elements of 1'st row = 1
for (int c = 0; c < n ; c++)
grid[0][c] = 1;
for (int r = 1; r < m ; r++) {
for (int c = 1; c < n; c++) {
grid[r][c] = grid[r-1][c] + grid[r][c-1];
}
}
return grid[m-1][n-1];
}
int main() {
int rows = 7, cols = 3, paths;
paths = UniquePaths(rows, cols);
cout << "Paths : " << paths << endl;
rows = 3, cols = 3;
paths = UniquePaths(rows, cols);
cout << "Paths : " << paths << endl;
return 0;
}
Output
Grid Rows : 7, Columns : 3
Paths : 28
Grid Rows : 3, Columns : 3
Paths : 6