Matrix Zig Zag Diagonal Traversal

Last Updated : 9 May, 2026

Given a matrix of n*n size, the task is to print its elements in a diagonal pattern. 

Input:

2056957913

Output : 1 2 4 7 5 3 6 8 9.
Explanation: Start from 1 Then from upward to downward diagonally i.e. 2 and 4 Then from downward to upward diagonally i.e 7, 5, 3 Then from up to down diagonally i.e 6, 8 Then down to up i.e. end at 9.

Input:

2056957914

Output: 1 2 4 7 5 3 10 6 8 13 14 9 11 12 15 16 .
Explanation: Start from 1 Then from upward to downward diagonally i.e. 2 and 4 Then from downward to upward diagonally i.e 7, 5, 3 Then from upward to downward diagonally i.e. 10 6 8 13 Then from downward to upward diagonally i.e 14 9 11 Then from upward to downward diagonally i.e. 12 15 then end at 16

Try It Yourself
redirect icon

[Efficient Approach] Using Diagonal Traversal Simulation – O(n²) Time and O(1) Space

The idea is to alternate between upward and downward directions. Starting from the top-left corner, we move along diagonals and switch direction whenever we hit a boundary (top row, bottom row, left column, or right column). By carefully updating indices and toggling direction, we ensure that all elements are visited exactly once in diagonal order.

  • Start from (0, 0) and maintain a direction flag to track upward or downward movement
  • Traverse diagonally in the current direction and store elements in the result
  • When a boundary is reached, adjust indices to the next valid starting point
  • Flip the direction after completing each diagonal and continue until all elements are covered
C++
// C++ program to print matrix in diagonal order
#include <bits/stdc++.h>
using namespace std;

vector<int> matrixDiagonally(vector<vector<int>>& mat) {

    int n = mat.size();

    // Initialize indexes of element to be printed next
    int i = 0, j = 0;

    // Direction is initially from down to up
    bool isUp = true;

    vector<int> ans;

    // Traverse the matrix till all elements get traversed
    for (int k = 0; k < n * n;) {

        // If isUp = true then traverse from downward to upward
        if (isUp) {
            for (; i >= 0 && j < n; j++, i--) {
                ans.push_back(mat[i][j]);
                k++;
            }

            // Set i and j according to direction
            if (i < 0 && j <= n - 1)
                i = 0;
            if (j == n)
                i = i + 2, j--;
        }

        // If isUp = false then traverse up to down
        else {
            for (; j >= 0 && i < n; i++, j--) {
                ans.push_back(mat[i][j]);
                k++;
            }

            // Set i and j according to direction
            if (j < 0 && i <= n - 1)
                j = 0;
            if (i == n)
                j = j + 2, i--;
        }

        // Revert the isUp to change the direction
        isUp = !isUp;
    }

    return ans;
}

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

    vector<int> res = matrixDiagonally(mat);

    for (int x : res)
        cout << x << " ";

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

class GFG {

    static int[] matrixDiagonally(int[][] mat) {

        int n = mat.length;

        // Initialize indexes of element to be printed next
        int i = 0, j = 0;

        // Direction is initially from down to up
        boolean isUp = true;

        ArrayList<Integer> list = new ArrayList<>();

        // Traverse the matrix till all elements get traversed
        for (int k = 0; k < n * n;) {

            // If isUp = true then traverse from downward to upward
            if (isUp) {
                for (; i >= 0 && j < n; j++, i--) {
                    list.add(mat[i][j]);
                    k++;
                }

                // Set i and j according to direction
                if (i < 0 && j <= n - 1)
                    i = 0;
                if (j == n) {
                    i = i + 2;
                    j--;
                }
            }

            // If isUp = false then traverse up to down
            else {
                for (; j >= 0 && i < n; i++, j--) {
                    list.add(mat[i][j]);
                    k++;
                }

                // Set i and j according to direction
                if (j < 0 && i <= n - 1)
                    j = 0;
                if (i == n) {
                    j = j + 2;
                    i--;
                }
            }

            // Revert the isUp to change the direction
            isUp = !isUp;
        }

        int[] ans = new int[list.size()];
        for (int x = 0; x < list.size(); x++) {
            ans[x] = list.get(x);
        }

        return ans;
    }
}
Python
def matrixDiagonally(mat):

    n = len(mat)

    # Initialize indexes of element to be printed next
    i, j = 0, 0

    # Direction is initially from down to up
    isUp = True

    ans = []

    # Traverse the matrix till all elements get traversed
    k = 0
    while k < n * n:

        # If isUp = true then traverse from downward to upward
        if isUp:
            while i >= 0 and j < n:
                ans.append(mat[i][j])
                k += 1
                j += 1
                i -= 1

            # Set i and j according to direction
            if i < 0 and j <= n - 1:
                i = 0
            if j == n:
                i = i + 2
                j -= 1

        # If isUp = false then traverse up to down
        else:
            while j >= 0 and i < n:
                ans.append(mat[i][j])
                k += 1
                i += 1
                j -= 1

            # Set i and j according to direction
            if j < 0 and i <= n - 1:
                j = 0
            if i == n:
                j = j + 2
                i -= 1

        # Revert the isUp to change the direction
        isUp = not isUp

    return ans


# Driver code
mat = [
    [1,2,3],
    [4,5,6],
    [7,8,9]
]

res = matrixDiagonally(mat)
print(*res)
C#
using System;
using System.Collections.Generic;

class Solution {

    public int[] MatrixDiagonally(int[,] mat) {

        int n = mat.GetLength(0);

        // Initialize indexes of element to be printed next
        int i = 0, j = 0;

        // Direction is initially from down to up
        bool isUp = true;

        List<int> list = new List<int>();

        int k = 0;

        // Traverse the matrix till all elements get traversed
        while (k < n * n) {

            // If isUp = true then traverse from downward to upward
            if (isUp) {
                while (i >= 0 && j < n) {
                    list.Add(mat[i, j]);
                    k++;
                    j++;
                    i--;
                }

                // Set i and j according to direction
                if (i < 0 && j <= n - 1)
                    i = 0;
                if (j == n) {
                    i = i + 2;
                    j--;
                }
            }

            // If isUp = false then traverse up to down
            else {
                while (j >= 0 && i < n) {
                    list.Add(mat[i, j]);
                    k++;
                    i++;
                    j--;
                }

                // Set i and j according to direction
                if (j < 0 && i <= n - 1)
                    j = 0;
                if (i == n) {
                    j = j + 2;
                    i--;
                }
            }

            // Revert the isUp to change the direction
            isUp = !isUp;
        }

        return list.ToArray(); // Convert List → int[]
    }
}
JavaScript
function matrixDiagonally(mat) {

    let n = mat.length;

    // Initialize indexes of element to be printed next
    let i = 0, j = 0;

    // Direction is initially from down to up
    let isUp = true;

    let ans = [];

    let k = 0;

    // Traverse the matrix till all elements get traversed
    while (k < n * n) {

        // If isUp = true then traverse from downward to upward
        if (isUp) {
            while (i >= 0 && j < n) {
                ans.push(mat[i][j]);
                k++;
                j++;
                i--;
            }

            // Set i and j according to direction
            if (i < 0 && j <= n - 1)
                i = 0;
            if (j === n) {
                i = i + 2;
                j--;
            }
        }

        // If isUp = false then traverse up to down
        else {
            while (j >= 0 && i < n) {
                ans.push(mat[i][j]);
                k++;
                i++;
                j--;
            }

            // Set i and j according to direction
            if (j < 0 && i <= n - 1)
                j = 0;
            if (i === n) {
                j = j + 2;
                i--;
            }
        }

        // Revert the isUp to change the direction
        isUp = !isUp;
    }

    return ans;
}

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

let res = matrixDiagonally(mat);
console.log(res.join(" "));

Output
1 2 4 7 5 3 6 8 9

[Optimized Approach] Using Diagonal Indexing – O(n²) Time and O(1) Space

The idea is to traverse the matrix by processing all diagonals one by one instead of simulating movement. A square matrix has 2n - 1 diagonals, and each diagonal can be identified using the sum of indices. By controlling the starting point and direction based on the diagonal number, we can directly access elements in the required zig-zag order. This avoids complex boundary handling and makes traversal more structured.

  • Iterate over all diagonals from 0 to 2n - 2
  • For each diagonal, determine starting row and column indices
  • Traverse elements in that diagonal and decide direction based on parity
  • Add elements to result while maintaining zig-zag (up/down) order
C++
#include <bits/stdc++.h>
using namespace std;

vector<int> matrixDiagonally(vector<vector<int>>& mat)
{
    int n = mat.size();

    // mode - switch to derive up/down traversal
    // it - iterator count - increases until it
    // reaches n and then decreases
    int mode = 0, it = 0, lower = 0;

    vector<int> ans;

    // 2n-1 will be the number of diagonals
    for (int t = 0; t < (2 * n - 1); t++) {

        int t1 = t;

        if (t1 >= n) {
            mode++;
            t1 = n - 1;
            it--;
            lower++;
        }
        else {
            lower = 0;
            it++;
        }

        for (int i = t1; i >= lower; i--) {

            if ((t1 + mode) % 2 == 0) {
                ans.push_back(mat[i][t1 + lower - i]);
            }
            else {
                ans.push_back(mat[t1 + lower - i][i]);
            }
        }
    }

    return ans;
}

// Driver code
int main()
{
    vector<vector<int>> mat = {
        {1, 2, 3, 4},
        {5, 6, 7, 8},
        {9,10,11,12},
        {13,14,15,16}
    };

    vector<int> res = matrixDiagonally(mat);

    for (int x : res)
        cout << x << " ";

    return 0;
}
Java
// C++ program to print matrix in diagonal order
#include <bits/stdc++.h>
using namespace std;

vector<int> matrixDiagonally(vector<vector<int>>& mat)
{
    int n = mat.size();

    // mode - switch to derive up/down traversal
    // it - iterator count - increases until it
    // reaches n and then decreases
    int mode = 0, it = 0, lower = 0;

    vector<int> ans;

    // 2n-1 will be the number of diagonals
    for (int t = 0; t < (2 * n - 1); t++) {

        int t1 = t;

        if (t1 >= n) {
            mode++;
            t1 = n - 1;
            it--;
            lower++;
        }
        else {
            lower = 0;
            it++;
        }

        for (int i = t1; i >= lower; i--) {

            if ((t1 + mode) % 2 == 0) {
                ans.push_back(mat[i][t1 + lower - i]);
            }
            else {
                ans.push_back(mat[t1 + lower - i][i]);
            }
        }
    }

    return ans;
}

// Driver code
int main()
{
    vector<vector<int>> mat = {
        {1, 2, 3, 4},
        {5, 6, 7, 8},
        {9,10,11,12},
        {13,14,15,16}
    };

    vector<int> res = matrixDiagonally(mat);

    for (int x : res)
        cout << x << " ";

    return 0;
}
Python
def matrixDiagonally(mat):

    n = len(mat)

    # mode - switch to derive up/down traversal
    # it - iterator count - increases until it
    # reaches n and then decreases
    mode = 0
    it = 0
    lower = 0

    ans = []

    # 2n-1 will be the number of diagonals
    for t in range(2 * n - 1):

        t1 = t

        if t1 >= n:
            mode += 1
            t1 = n - 1
            it -= 1
            lower += 1
        else:
            lower = 0
            it += 1

        for i in range(t1, lower - 1, -1):

            if (t1 + mode) % 2 == 0:
                ans.append(mat[i][t1 + lower - i])
            else:
                ans.append(mat[t1 + lower - i][i])

    return ans


# Driver code
mat = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9,10,11,12],
    [13,14,15,16]
]

res = matrixDiagonally(mat)
print(*res)
C#
using System;
using System.Collections.Generic;

class Solution {

    public int[] MatrixDiagonally(int[,] mat)
    {
        int n = mat.GetLength(0);

        // mode - switch to derive up/down traversal
        // it - iterator count - increases until it
        // reaches n and then decreases
        int mode = 0, it = 0, lower = 0;

        List<int> list = new List<int>();

        // 2n-1 will be the number of diagonals
        for (int t = 0; t < (2 * n - 1); t++) {

            int t1 = t;

            if (t1 >= n) {
                mode++;
                t1 = n - 1;
                it--;
                lower++;
            }
            else {
                lower = 0;
                it++;
            }

            for (int i = t1; i >= lower; i--) {

                if ((t1 + mode) % 2 == 0) {
                    list.Add(mat[i, t1 + lower - i]);
                }
                else {
                    list.Add(mat[t1 + lower - i, i]);
                }
            }
        }

        return list.ToArray();
    }
}
JavaScript
function matrixDiagonally(mat)
{
    let n = mat.length;

    // mode - switch to derive up/down traversal
    // it - iterator count - increases until it
    // reaches n and then decreases
    let mode = 0, it = 0, lower = 0;

    let ans = [];

    // 2n-1 will be the number of diagonals
    for (let t = 0; t < (2 * n - 1); t++) {

        let t1 = t;

        if (t1 >= n) {
            mode++;
            t1 = n - 1;
            it--;
            lower++;
        }
        else {
            lower = 0;
            it++;
        }

        for (let i = t1; i >= lower; i--) {

            if ((t1 + mode) % 2 === 0) {
                ans.push(mat[i][t1 + lower - i]);
            }
            else {
                ans.push(mat[t1 + lower - i][i]);
            }
        }
    }

    return ans;
}

// Driver code
let mat = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9,10,11,12],
    [13,14,15,16]
];

let res = matrixDiagonally(mat);
console.log(res.join(" "));

Output
1 2 5 9 6 3 4 7 10 13 14 11 8 12 15 16 
Comment