Example:
Path 1: (0,0) -> (0,1) -> (1,1) Path 2: (0,0) -> (1,0) -> (1,1)
We found a pattern to go through for every index we can choose to solve with iteration / recursion.
Here we will solve it through RECURSION!
const num_of_paths = findMaxPathSrcToDes(3, 3);
console.log('Number of Paths', num_of_paths);
We call findMaxPathSrcToDes
and pass row length and column length and log it.
function findMaxPathSrcToDes(rows, cols) {
// Initial rows and columns to begin with.0,0 is the first row and col index we are choosing
return findMaxPath(0, 0, rows - 1, cols - 1);
}
findMaxPathSrcToDes
function accepts the row length and column length from the user.findMaxPath
function to which we pass the origin which is (0,0) and destination index(rows -1, cols - 1).findMaxPath
function takes in 4 params and outputs the number of path.
currentRow
- Which indicates the current index's Row that is being processed.currentRow
- Which indicates the current index's Column that is being processed.destRow
- Destination row indexdestCol
- Destination column indexIn any Recursive solution, start with writing the base conditions or Exit conditions.
So, what is a Base condition or Exit condition?
It is basically the case on satisfying which our algorithm should terminate. So, let's formulate one.
currentRow > destRow
(In this case it indicates that the currentRow
count has gone out of bound).currentColumn > destCol
(In this case it indicates that the currentColumn
count has gone out of bound).
So we return '0' in both the cases.function findMaxPath(currentRow, currentColumn, destRow, destCol) {
// Base condition
if (currentRow > destRow || currentColumn > destCol) {
return 0;
}
}
currentRow === destRow
or currentColumn === destCol
this indicates that we have reached the destination index so we return 1
to indicate a successful path.if (currentRow === destRow && currentColumn === destCol) {
return 1;
}
findMaxPath
by incrementing currentRow
by 1.currentColumn
by 1 and adding the outputs of these two and return them.const pathsInRows = findMaxPath(currentRow + 1, currentColumn, destRow, destCol);
const pathsInColums = findMaxPath(currentRow, currentColumn + 1, destRow, destCol);
return (pathsInRows + pathsInColums);
CodePen link here
Next Step: