Traverse a given Matrix using Recursion

31 May, 2021
Given a matrix arr of size N x M, the task is to traverse this matrix using recursion.Examples: 
Input: arr[][] = {{1, 2, 3}, 
                  {4, 5, 6},
                  {7, 8, 9}} 
Output: 1, 2, 3, 4, 5, 6, 7, 8, 9

Input: M[][] = {{11, 12, 13}, 
                  {14, 15, 16}, 
                  {17, 18, 19}}
Output: 11, 12, 13, 14, 15, 16, 17, 18, 19
Approach: Below are the steps to traverse the Matrix recursively:  
Base Case: If the current row or column exceeds the size N or M, respectively, the recursion is stopped.If the current column exceeds the total number of columns M, then the next row is started.
If the current column exceeds the total number of columns M, then the next row is started.
if (current_col >= M)
    This row ends.
    Start for next row
If the current row exceeds the total number of rows N, then the complete traversal is stopped.
if (current_row >= N)
    Matrix has been
    traversed completely
Recursive Case: In each recursive call, The current element of the Matrix is printed.Two recursive calls are made: One to traverse the next row, andAnother to traverse the next column.
The current element of the Matrix is printed.Two recursive calls are made: One to traverse the next row, andAnother to traverse the next column.
The current element of the Matrix is printed.
Two recursive calls are made: One to traverse the next row, andAnother to traverse the next column.
One to traverse the next row, and
Another to traverse the next column.
Below is the implementation of the above approach: 
C++
Java
C#
Python3
Javascript
// C++ program to traverse the matrix recursively #include <iostream>using namespace std; #define N 2#define M 3 // Function to traverse the matrix recursivelyint traverseMatrix(int arr[N][M], int current_row,                   int current_col){    // If the entire column is traversed    if (current_col >= M)        return 0;     // If the entire row is traversed    if (current_row >= N)        return 1;     // Print the value of the current    // cell of the matrix    cout << arr[current_row][current_col] << ", ";     // Recursive call to traverse the matrix    // in the Horizontal direction    if (traverseMatrix(arr, current_row,                       current_col + 1)        == 1)        return 1;     // Recursive call for changing the    // Row of the matrix    return traverseMatrix(arr,                          current_row + 1,                          0);} // Driver codeint main(){    int arr[N][M] = { { 1, 2, 3 },                      { 4, 5, 6 } };     traverseMatrix(arr, 0, 0);    return 0;}
// Java program to traverse the matrix recursivelyclass GFG {         final static int N = 2;    final static int  M = 3;         // Function to traverse the matrix recursively    static int traverseMatrix(int arr[][], int current_row,                       int current_col)    {        // If the entire column is traversed        if (current_col >= M)            return 0;             // If the entire row is traversed        if (current_row >= N)            return 1;             // Print the value of the current        // cell of the matrix        System.out.print(arr[current_row][current_col] + ", ");             // Recursive call to traverse the matrix        // in the Horizontal direction        if (traverseMatrix(arr, current_row,                           current_col + 1)            == 1)            return 1;             // Recursive call for changing the        // Row of the matrix        return traverseMatrix(arr,                              current_row + 1,                              0);    }         // Driver code    public static void main (String[] args)    {        int arr[][] = { { 1, 2, 3 },                          { 4, 5, 6 } };             traverseMatrix(arr, 0, 0);    }} // This code is contributed by AnkitRai01
// C# program to traverse the matrix recursively using System; public class GFG {         static int N = 2;    static int  M = 3;         // Function to traverse the matrix recursively    static int traverseMatrix(int [,]arr, int current_row,                       int current_col)    {        // If the entire column is traversed        if (current_col >= M)            return 0;             // If the entire row is traversed        if (current_row >= N)            return 1;             // Print the value of the current        // cell of the matrix        Console.Write(arr[current_row,current_col] + ", ");             // Recursive call to traverse the matrix        // in the Horizontal direction        if (traverseMatrix(arr, current_row,                           current_col + 1)            == 1)            return 1;             // Recursive call for changing the        // Row of the matrix        return traverseMatrix(arr,                              current_row + 1,                              0);    }         // Driver code    public static void Main (string[] args)    {        int [,]arr = { { 1, 2, 3 },                          { 4, 5, 6 } };             traverseMatrix(arr, 0, 0);    }} // This code is contributed by AnkitRai01
# Python3 program to traverse the matrix recursivelyN = 2M = 3 # Function to traverse the matrix recursivelydef traverseMatrix(arr, current_row, current_col) :     # If the entire column is traversed    if (current_col >= M) :        return 0;     # If the entire row is traversed    if (current_row >= N) :        return 1;     # Print the value of the current    # cell of the matrix    print(arr[current_row][current_col],end= ", ");     # Recursive call to traverse the matrix    # in the Horizontal direction    if (traverseMatrix(arr, current_row, current_col + 1 ) == 1) :        return 1;             # Recursive call for changing the    # Row of the matrix    return traverseMatrix(arr, current_row + 1, 0); # Driver codeif __name__ == "__main__" :    arr = [ [ 1, 2, 3 ],            [ 4, 5, 6 ] ];     traverseMatrix(arr, 0, 0); # This code is contributed by AnkitRai01
<script>// Javascript program to traverse the matrix recursively let N = 2let M = 3 // Function to traverse the matrix recursivelyfunction traverseMatrix(arr, current_row, current_col){    // If the entire column is traversed    if (current_col >= M)        return 0;     // If the entire row is traversed    if (current_row >= N)        return 1;     // Print the value of the current    // cell of the matrix    document.write(arr[current_row][current_col] + ", ");     // Recursive call to traverse the matrix    // in the Horizontal direction    if (traverseMatrix(arr, current_row,                    current_col + 1)        == 1)        return 1;     // Recursive call for changing the    // Row of the matrix    return traverseMatrix(arr,                        current_row + 1,                        0);} // Driver code let arr = [ [ 1, 2, 3 ],            [ 4, 5, 6 ] ]; traverseMatrix(arr, 0, 0);</script>
1, 2, 3, 4, 5, 6,
 
Time Complexity: O(N * M)
Auxiliary Space: O(M), because of recursive calling
ankthon
souravmahato348
_saurabh_jaiswal
Traversal
Arrays
Matrix
Recursion
Arrays
Recursion
Matrix
Traversal
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Program to find largest element in an array
Matrix Chain Multiplication | DP-8
Rat in a Maze | Backtracking-2
Sudoku | Backtracking-7
Find the number of islands | Set 1 (Using DFS)