Be the first user to complete this post

  • 0
Add to List

Print All Paths from Top left to bottom right in Two Dimensional 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.


Print All Paths - Example


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 =""
  4. Call printAll(currentRow, currentcolumn,path)
  5. Add array[0][0] to the path.
  6. Call recursively printAll(currentRow+1, currentcolumn,path)
  7. Call recursively printAll(currentRow, currentcolumn+1,path)
  8. Base Case 1: when currentRow = rowCount-1(because array index starts with 0) , print the rest of the columns, return
  9. Base Case 2: when currentcolumn = colCount-1(because array index starts with 0) , print the rest of the rows, return

Like always you need to trust Recursion to get you the correct result. :)

Recursion Tree -Print All Paths

click on the image to make it bigger



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

Also Read: