This post is completed by 1 user

  • 0
Add to List
Medium

18. All Paths from Top Left to Bottom Right in 2D Array

Objective: Print all the paths from left top corner to right bottom corner in two dimensional array.

Input: Two Dimensional array
Output: Print all the paths.

Note: At the End of the article you will know what needs to be included if you want to print the diagonal paths as well.

Example:

Print All Paths - Example

Approach:

As we need to explore all the paths from top left corner to bottom right corner, we will either travel down OR travel right. so every time either we increase the row or column.

  1. Recursion is the key here.
  2. Take the rows count and column counts say rowCount and colCount respectively
  3. Take currentRow=0 and currentColumn=0 and path = array[0][0]
  4. Call recursively with currentRow+1 -- go down
  5. Call recursively currentcolumn+1 -- go right
  6. Base Case 1: when currentRow = rowCount-1(because array index starts with 0) , print the rest of the columns, return
  7. Base Case 2: when currentcolumn = colCount-1(because array index starts with 0) , print the rest of the rows, return
Recursion Tree -Print All Paths

click on the image to make it bigger

-1-4-7-8-9
-1-4-5-8-9
-1-4-5-6-9
-1-2-5-8-9
-1-2-5-6-9
-1-2-3-6-9

Note: printAll(currentRow+1,currentColumn+1,path); Add this line when you want to print diagonal paths as well (see code)