Print matrix in snake pattern

Last Updated : 30 Sep, 2026

Given a square matrix mat[][] of size n × n, print all its elements in a snake pattern. The first row is printed from left to right, the second row from right to left, and this pattern continues for all rows.

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] 
Explanation: The first row is printed from left to right, the second row from right to left, and the same pattern continues for the remaining rows.

blobid0_1749128162

Input: mat[][] = [[1, 2], [3, 4]]
Output: [1, 2, 4, 3]
Explanation: The first row is printed from left to right as 1 2, while the second row is printed from right to left as 4 3.

Try It Yourself
redirect icon

Traverse Rows Alternately - O(n^2) Time and O(1) Auxiliary Space

The idea is to traverse the matrix row by row, changing the direction after each row. For even-indexed rows, print elements from left to right, and for odd-indexed rows, print elements from right to left.

Consider the matrix: mat[][] = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

  • Row 0 is even, so print from left to right: 1 2 3.
  • Row 1 is odd, so print from right to left: 6 5 4.
  • Row 2 is even, so print from left to right: 7 8 9.

Therefore, the elements are printed as:[1, 2, 3, 6, 5, 4, 7, 8, 9]

C++
#include <iostream>
#include <vector>
using namespace std;

vector<int> snakePattern(vector<vector<int>> matrix) {
    
    int n = matrix.size();
    vector<int> res;

    // Traverse over the rows.
    for (int i = 0; i < n; i++) {
        
        // If current row is even, add elements
        // from left to right.
        if (i % 2 == 0) {
            for (int j = 0; j < n; j++)
                res.push_back(matrix[i][j]);
        }
        
        // If current row is odd, add elements
        // from right to left.
        else {
            for (int j = n - 1; j >= 0; j--)
                res.push_back(matrix[i][j]);
        }
    }

    return res;
}

int main() {
    vector<vector<int>> matrix = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };

    vector<int> res = snakePattern(matrix);

    cout << "[";

    for (int i = 0; i < res.size(); i++) {
        cout << res[i];

        if (i != res.size() - 1)
            cout << ", ";
    }

    cout << "]";

    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>

int* snakePattern(int n, int matrix[n][n])
{
    int* res = (int*)malloc(n * n * sizeof(int));
    int k = 0;

    // Traverse over the rows.
    for (int i = 0; i < n; i++)
    {
        // If current row is even, add elements
        // from left to right.
        if (i % 2 == 0)
        {
            for (int j = 0; j < n; j++)
                res[k++] = matrix[i][j];
        }

        // If current row is odd, add elements
        // from right to left.
        else
        {
            for (int j = n - 1; j >= 0; j--)
                res[k++] = matrix[i][j];
        }
    }

    return res;
}

int main()
{
    int n = 3;

    int matrix[3][3] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };

    int* res = snakePattern(n, matrix);

    printf("[");

    for (int i = 0; i < n * n; i++)
    {
        printf("%d", res[i]);

        if (i != n * n - 1)
            printf(", ");
    }

    printf("]");

    free(res);

    return 0;
}
Java
import java.util.ArrayList;

class GFG {

    static ArrayList<Integer> snakePattern(int[][] matrix) {
        
        int n = matrix.length;
        ArrayList<Integer> res = new ArrayList<>();

        // Traverse over the rows.
        for (int i = 0; i < n; i++) {
            
            // If current row is even, add elements
            // from left to right.
            if (i % 2 == 0) {
                for (int j = 0; j < n; j++)
                    res.add(matrix[i][j]);
            }
            
            // If current row is odd, add elements
            // from right to left.
            else {
                for (int j = n - 1; j >= 0; j--)
                    res.add(matrix[i][j]);
            }
        }

        return res;
    }

    public static void main(String[] args) {
        int[][] matrix = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };

        ArrayList<Integer> res = snakePattern(matrix);

        System.out.println(res);
    }
}
Python
def snakePattern(matrix):
    
    n = len(matrix)
    res = []

    # Traverse over the rows.
    for i in range(n):
        
        # If current row is even, add elements
        # from left to right.
        if i % 2 == 0:
            for j in range(n):
                res.append(matrix[i][j])
        
        # If current row is odd, add elements
        # from right to left.
        else:
            for j in range(n - 1, -1, -1):
                res.append(matrix[i][j])

    return res


if __name__ == "__main__":
    matrix = [
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]
    ]

    res = snakePattern(matrix)

    print(res)
C#
using System;
using System.Collections.Generic;

class GFG {

    static List<int> snakePattern(int[][] matrix) {
        
        int n = matrix.Length;
        List<int> res = new List<int>();

        // Traverse over the rows.
        for (int i = 0; i < n; i++) {
            
            // If current row is even, add elements
            // from left to right.
            if (i % 2 == 0) {
                for (int j = 0; j < n; j++)
                    res.Add(matrix[i][j]);
            }
            
            // If current row is odd, add elements
            // from right to left.
            else {
                for (int j = n - 1; j >= 0; j--)
                    res.Add(matrix[i][j]);
            }
        }

        return res;
    }

    static void Main() {
        int[][] matrix = {
            new int[] {1, 2, 3},
            new int[] {4, 5, 6},
            new int[] {7, 8, 9}
        };

        List<int> res = snakePattern(matrix);

        Console.WriteLine("[" + string.Join(", ", res) + "]");
    }
}
JavaScript
function snakePattern(matrix) {
    
    let n = matrix.length;
    let res = [];

    // Traverse over the rows.
    for (let i = 0; i < n; i++) {
        
        // If current row is even, add elements
        // from left to right.
        if (i % 2 == 0) {
            for (let j = 0; j < n; j++)
                res.push(matrix[i][j]);
        }
        
        // If current row is odd, add elements
        // from right to left.
        else {
            for (let j = n - 1; j >= 0; j--)
                res.push(matrix[i][j]);
        }
    }

    return res;
}

// Driver code
    let matrix = [
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]
    ];

    let res = snakePattern(matrix);

    console.log("[" + res.join(", ") + "]");

Output
[1, 2, 3, 6, 5, 4, 7, 8, 9]
Comment