Open In App

Javascript Program to Print matrix in snake pattern

Last Updated : 10 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given n x n matrix In the given matrix, you have to print the elements of the matrix in the snake pattern.

Examples: 

Input :mat[][] = { {10, 20, 30, 40},
{15, 25, 35, 45},
{27, 29, 37, 48},
{32, 33, 39, 50}};

Output : 10 20 30 40 45 35 25 15 27 29
37 48 50 39 33 32

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

Matrix printing

We traverse all rows. For every row, we check if it is even or odd. If even, we print from left to right else print from right to left. 

JavaScript
let M = 4;
let N = 4;

function print(mat) {
    let output = "";

    // Traverse through all rows
    for (let i = 0; i < M; i++) {

        // If current row is even, print from left to right
        if (i % 2 == 0) {
            for (let j = 0; j < N; j++)
                output += mat[i][j] + " ";

        // If current row is odd, print from right to left
        } else {
            for (let j = N - 1; j >= 0; j--)
                output += mat[i][j] + " ";
        }
    }
    console.log(output.trim());
}

// Driver code
let mat = [
    [10, 20, 30, 40],
    [15, 25, 35, 45],
    [27, 29, 37, 48],
    [32, 33, 39, 50]
];

print(mat);

Output
10 20 30 40 45 35 25 15 27 29 37 48 50 39 33 32

Complexity Analysis:

  • Time complexity: O(n^2) for given n*n matrix
  • Auxiliary space: O(1)

Please refer complete article on Print matrix in snake pattern for more details!


Next Article
Practice Tags :

Similar Reads