Open In App

Diagonal Traversal of a Matrix I

Last Updated : 08 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a 2D matrix of size n*m, the tasks is to print all elements of the given matrix in diagonal order.

Example:

Input: mat[][] = [[ 1, 2, 3, 4 ],
[5, 6, 7, 8 ],
[9, 10, 11, 12],
[13, 14, 15, 16],
[17, 18, 19, 20]]
Output: 1 5 2 9 6 3 13 10 7 4 17 14 11 8 18 15 12 19 16 20

Diagonal-Traversal-of-a-Matrix-2

Using Line by Line Diagonal Traversal - O(n*m) time and O(n*m) space

The idea is to traverse the matrix diagonally from bottom-left to top-right, one diagonal at a time. Since a matrix with R rows and C columns has exactly R+C-1 diagonals, we iterate through each diagonal line and identify the starting position, number of elements, and the indices of elements belonging to that diagonal, collecting them in sequence to produce the desired diagonal ordering.

Step by step approach:

  1. Identify total number of diagonals (rows + columns - 1) and iterate through each one.
  2. For each diagonal, calculate its starting column position based on the diagonal number.
  3. Determine how many elements exist in the current diagonal.
  4. Extract each element from the current diagonal by calculating its exact row and column indices.
  5. Collect all elements in a result container to return the diagonal ordering.
C++
// C++ program to find Diagonal Traversal of a Matrix
#include <bits/stdc++.h>
using namespace std;

// Function that returns elements of given mat in diagonal order
vector<int> diagonalOrder(const vector<vector<int>>& mat) {
    vector<int> res;
    
    int n = mat.size();
    int m = mat[0].size();
    
    // There will be n+m-1 diagonals in total
    for(int line = 1; line <= (n + m - 1); line++) {
        
        // Get column index of the first element in 
        // this diagonal. The index is 0 for first 'n' 
        // lines and (line - n) for remaining lines
        int startCol = max(0, line - n);
        
        // Get count of elements in this diagonal
        // Count equals minimum of line number, (m-startCol) and n
        int count = min({line, (m - startCol), n});
        
        // Process elements of this diagonal
        for(int j = 0; j < count; j++) {
            
            // Calculate row and column indices 
            // for each element in the diagonal
            int row = min(n, line) - j - 1;
            int col = startCol + j;
            res.push_back(mat[row][col]);
        }
    }
    
    return res;
}

int main() {

    vector<vector<int>> mat = {
        { 1, 2, 3, 4 },
        { 5, 6, 7, 8 },
        { 9, 10, 11, 12 },
        { 13, 14, 15, 16 },
        { 17, 18, 19, 20 }
    };
    vector<int> res = diagonalOrder(mat);
    for (auto val: res) cout << val << " ";
    cout << endl;
    
    return 0;
}
Java
// Java program to find Diagonal Traversal of a Matrix
import java.util.*;

class GfG {

    // Function that returns elements of given mat in diagonal order
    static ArrayList<Integer> diagonalOrder(int[][] mat) {
        ArrayList<Integer> res = new ArrayList<>();

        int n = mat.length;
        int m = mat[0].length;

        // There will be n+m-1 diagonals in total
        for (int line = 1; line <= (n + m - 1); line++) {

            // Get column index of the first element in 
            // this diagonal. The index is 0 for first 'n' 
            // lines and (line - n) for remaining lines
            int startCol = Math.max(0, line - n);

            // Get count of elements in this diagonal
            // Count equals minimum of line number, (m-startCol) and n
            int count = Math.min(Math.min(line, m - startCol), n);

            // Process elements of this diagonal
            for (int j = 0; j < count; j++) {

                // Calculate row and column indices 
                // for each element in the diagonal
                int row = Math.min(n, line) - j - 1;
                int col = startCol + j;
                res.add(mat[row][col]);
            }
        }

        return res;
    }

    public static void main(String[] args) {
        int[][] mat = {
            { 1, 2, 3, 4 },
            { 5, 6, 7, 8 },
            { 9, 10, 11, 12 },
            { 13, 14, 15, 16 },
            { 17, 18, 19, 20 }
        };
        ArrayList<Integer> res = diagonalOrder(mat);
        for (int val : res) System.out.print(val + " ");
        System.out.println();
    }
}
Python
# Python program to find Diagonal Traversal of a Matrix

# Function that returns elements of given mat in diagonal order
def diagonalOrder(mat):
    res = []

    n = len(mat)
    m = len(mat[0])

    # There will be n+m-1 diagonals in total
    for line in range(1, n + m):
        
        # Get column index of the first element in 
        # this diagonal. The index is 0 for first 'n' 
        # lines and (line - n) for remaining lines
        startCol = max(0, line - n)

        # Get count of elements in this diagonal
        # Count equals minimum of line number, (m-startCol) and n
        count = min(line, m - startCol, n)

        # Process elements of this diagonal
        for j in range(count):

            # Calculate row and column indices 
            # for each element in the diagonal
            row = min(n, line) - j - 1
            col = startCol + j
            res.append(mat[row][col])

    return res

if __name__ == "__main__":
    mat = [
        [ 1, 2, 3, 4 ],
        [ 5, 6, 7, 8 ],
        [ 9, 10, 11, 12 ],
        [ 13, 14, 15, 16 ],
        [ 17, 18, 19, 20 ]
    ]
    res = diagonalOrder(mat)
    print(" ".join(map(str, res)))
C#
// C# program to find Diagonal Traversal of a Matrix
using System;
using System.Collections.Generic;

class GfG {

    // Function that returns elements of given mat in diagonal order
    static List<int> diagonalOrder(int[][] mat) {
        List<int> res = new List<int>();

        int n = mat.Length;
        int m = mat[0].Length;

        // There will be n+m-1 diagonals in total
        for (int line = 1; line <= (n + m - 1); line++) {

            // Get column index of the first element in 
            // this diagonal. The index is 0 for first 'n' 
            // lines and (line - n) for remaining lines
            int startCol = Math.Max(0, line - n);

            // Get count of elements in this diagonal
            // Count equals minimum of line number, (m-startCol) and n
            int count = Math.Min(Math.Min(line, m - startCol), n);

            // Process elements of this diagonal
            for (int j = 0; j < count; j++) {

                // Calculate row and column indices 
                // for each element in the diagonal
                int row = Math.Min(n, line) - j - 1;
                int col = startCol + j;
                res.Add(mat[row][col]);
            }
        }

        return res;
    }

    static void Main(string[] args) {
        int[][] mat = new int[][] {
            new int[] { 1, 2, 3, 4 },
            new int[] { 5, 6, 7, 8 },
            new int[] { 9, 10, 11, 12 },
            new int[] { 13, 14, 15, 16 },
            new int[] { 17, 18, 19, 20 }
        };

        List<int> res = diagonalOrder(mat);
        foreach (int val in res) Console.Write(val + " ");
        Console.WriteLine();
    }
}
JavaScript
// JavaScript program to find Diagonal Traversal of a Matrix

// Function that returns elements of given mat in diagonal order
function diagonalOrder(mat) {
    let res = [];

    let n = mat.length;
    let m = mat[0].length;

    // There will be n+m-1 diagonals in total
    for (let line = 1; line <= (n + m - 1); line++) {

        // Get column index of the first element in 
        // this diagonal. The index is 0 for first 'n' 
        // lines and (line - n) for remaining lines
        let startCol = Math.max(0, line - n);

        // Get count of elements in this diagonal
        // Count equals minimum of line number, (m-startCol) and n
        let count = Math.min(line, m - startCol, n);

        // Process elements of this diagonal
        for (let j = 0; j < count; j++) {

            // Calculate row and column indices 
            // for each element in the diagonal
            let row = Math.min(n, line) - j - 1;
            let col = startCol + j;
            res.push(mat[row][col]);
        }
    }

    return res;
}

let mat = [
    [ 1, 2, 3, 4 ],
    [ 5, 6, 7, 8 ],
    [ 9, 10, 11, 12 ],
    [ 13, 14, 15, 16 ],
    [ 17, 18, 19, 20 ]
];

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

Output
1 5 2 9 6 3 13 10 7 4 17 14 11 8 18 15 12 19 16 20 

Using Starting Point Traversal - O(n*m) time and O(n*m) space

The idea is to traverse the matrix diagonally from bottom-left to top-right by identifying each diagonal's starting point and following it up. Since every diagonal moves in the same direction (up and right), the approach divides the matrix into two parts: first processing all diagonals that start from the first column (from top to bottom), then processing the remaining diagonals that start from the bottom row (from left to right, excluding the already processed bottom-left corner).

C++
// C++ program to find Diagonal Traversal of a Matrix
#include <bits/stdc++.h>
using namespace std;

// Function that returns elements of given mat in diagonal order
vector<int> diagonalOrder(const vector<vector<int>>& mat) {
    vector<int> res;
    int n = mat.size();
    int m = mat[0].size();
    
    // Process all diagonals starting from the first column
    for (int row = 0; row < n; row++) {
        int i = row, j = 0;
        
        // Follow each diagonal going up and right
        while (i >= 0 && j < m) {
            res.push_back(mat[i][j]);
            i--;
            j++;
        }
    }
    
    // Process remaining diagonals starting from 
    // the bottom row (except first column)
    for (int col = 1; col < m; col++) {
        int i = n-1, j = col;
        
        // Follow each diagonal going up and right
        while (i >= 0 && j < m) {
            res.push_back(mat[i][j]);
            i--;
            j++;
        }
    }
    
    return res;
}

int main() {
    vector<vector<int>> mat = {
        { 1, 2, 3, 4 },
        { 5, 6, 7, 8 },
        { 9, 10, 11, 12 },
        { 13, 14, 15, 16 },
        { 17, 18, 19, 20 }
    };
    vector<int> res = diagonalOrder(mat);
    for (auto val: res) cout << val << " ";
    cout << endl;
    
    return 0;
}
Java
// Java program to find Diagonal Traversal of a Matrix

import java.util.ArrayList;

class GfG {

    // Function that returns elements of given mat in diagonal order
    static ArrayList<Integer> diagonalOrder(int[][] mat) {
        ArrayList<Integer> res = new ArrayList<>();
        int n = mat.length;
        int m = mat[0].length;
        
        // Process all diagonals starting from the first column
        for (int row = 0; row < n; row++) {
            int i = row, j = 0;
            
            // Follow each diagonal going up and right
            while (i >= 0 && j < m) {
                res.add(mat[i][j]);
                i--;
                j++;
            }
        }
        
        // Process remaining diagonals starting from 
        // the bottom row (except first column)
        for (int col = 1; col < m; col++) {
            int i = n-1, j = col;
            
            // Follow each diagonal going up and right
            while (i >= 0 && j < m) {
                res.add(mat[i][j]);
                i--;
                j++;
            }
        }
        
        return res;
    }

    public static void main(String[] args) {
        int[][] mat = {
            { 1, 2, 3, 4 },
            { 5, 6, 7, 8 },
            { 9, 10, 11, 12 },
            { 13, 14, 15, 16 },
            { 17, 18, 19, 20 }
        };
        ArrayList<Integer> res = diagonalOrder(mat);
        for (int val : res) {
            System.out.print(val + " ");
        }
        System.out.println();
    }
}
Python
# Python program to find Diagonal Traversal of a Matrix

# Function that returns elements of given mat in diagonal order
def diagonalOrder(mat):
    res = []
    n = len(mat)
    m = len(mat[0])
    
    # Process all diagonals starting from the first column
    for row in range(n):
        i = row
        j = 0
        
        # Follow each diagonal going up and right
        while i >= 0 and j < m:
            res.append(mat[i][j])
            i -= 1
            j += 1

    # Process remaining diagonals starting from 
    # the bottom row (except first column)
    for col in range(1, m):
        i = n - 1
        j = col
        
        # Follow each diagonal going up and right
        while i >= 0 and j < m:
            res.append(mat[i][j])
            i -= 1
            j += 1

    return res

if __name__ == "__main__":
    mat = [
        [1, 2, 3, 4],
        [5, 6, 7, 8],
        [9, 10, 11, 12],
        [13, 14, 15, 16],
        [17, 18, 19, 20]
    ]
    res = diagonalOrder(mat)
    for val in res:
        print(val, end=" ")
    print()
C#
// C# program to find Diagonal Traversal of a Matrix

using System;
using System.Collections.Generic;

class GfG {

    // Function that returns elements of given mat in diagonal order
    static List<int> diagonalOrder(int[,] mat) {
        List<int> res = new List<int>();
        int n = mat.GetLength(0);
        int m = mat.GetLength(1);
        
        // Process all diagonals starting from the first column
        for (int row = 0; row < n; row++) {
            int i = row, j = 0;
            
            // Follow each diagonal going up and right
            while (i >= 0 && j < m) {
                res.Add(mat[i, j]);
                i--;
                j++;
            }
        }
        
        // Process remaining diagonals starting from 
        // the bottom row (except first column)
        for (int col = 1; col < m; col++) {
            int i = n-1, j = col;
            
            // Follow each diagonal going up and right
            while (i >= 0 && j < m) {
                res.Add(mat[i, j]);
                i--;
                j++;
            }
        }
        
        return res;
    }

    static void Main(string[] args) {
        int[,] mat = {
            { 1, 2, 3, 4 },
            { 5, 6, 7, 8 },
            { 9, 10, 11, 12 },
            { 13, 14, 15, 16 },
            { 17, 18, 19, 20 }
        };
        List<int> res = diagonalOrder(mat);
        foreach (int val in res) {
            Console.Write(val + " ");
        }
        Console.WriteLine();
    }
}
JavaScript
// JavaScript program to find Diagonal Traversal of a Matrix

// Function that returns elements of given mat in diagonal order
function diagonalOrder(mat) {
    let res = [];
    let n = mat.length;
    let m = mat[0].length;
    
    // Process all diagonals starting from the first column
    for (let row = 0; row < n; row++) {
        let i = row, j = 0;
        
        // Follow each diagonal going up and right
        while (i >= 0 && j < m) {
            res.push(mat[i][j]);
            i--;
            j++;
        }
    }
    
    // Process remaining diagonals starting from 
    // the bottom row (except first column)
    for (let col = 1; col < m; col++) {
        let i = n - 1, j = col;
        
        // Follow each diagonal going up and right
        while (i >= 0 && j < m) {
            res.push(mat[i][j]);
            i--;
            j++;
        }
    }
    
    return res;
}

let mat = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12],
    [13, 14, 15, 16],
    [17, 18, 19, 20]
];
let res = diagonalOrder(mat);
for (let val of res) {
    process.stdout.write(val + " ");
}
console.log();

Output
1 5 2 9 6 3 13 10 7 4 17 14 11 8 18 15 12 19 16 20 

Related Articles:


Next Article

Similar Reads