VOOZH about

URL: https://www.geeksforgeeks.org/dsa/traverse-a-given-matrix-using-recursion/

⇱ Traverse a given Matrix using Recursion - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Traverse a given Matrix using Recursion

Last Updated : 12 Jul, 2025

Given a matrixmat[][] of size n x m, the task is to traverse this matrix using recursion.
Examples:

Input: mat[][] = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
Output: 1 2 3 4 5 6 7 8 9

Input: mat[][] = [[11, 12, 13],
[14, 15, 16],
[17, 18, 19]]
Output: 11 12 13 14 15 16 17 18 19

Approach:

  • Check If the current position is in the bottom-right corner of the matrix
    • Print the value at that position
    • End the recursion
  • Print the value at the current position
  • Check If the end of the current row has not been reached
    • Move right
  • Check If the end of the current column has been reached
    • Move down to the next row

Below is the implementation of the above approach: 


Output
1 2 3 4 5 6 7 8 9

Time Complexity: O(N * M)
Auxiliary Space: O(M), because of recursive calling


Comment
Article Tags: