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:
Identify total number of diagonals (rows + columns - 1) and iterate through each one.
For each diagonal, calculate its starting column position based on the diagonal number.
Determine how many elements exist in the current diagonal.
Extract each element from the current diagonal by calculating its exact row and column indices.
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>usingnamespacestd;// Function that returns elements of given mat in diagonal ordervector<int>diagonalOrder(constvector<vector<int>>&mat){vector<int>res;intn=mat.size();intm=mat[0].size();// There will be n+m-1 diagonals in totalfor(intline=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 linesintstartCol=max(0,line-n);// Get count of elements in this diagonal// Count equals minimum of line number, (m-startCol) and nintcount=min({line,(m-startCol),n});// Process elements of this diagonalfor(intj=0;j<count;j++){// Calculate row and column indices // for each element in the diagonalintrow=min(n,line)-j-1;intcol=startCol+j;res.push_back(mat[row][col]);}}returnres;}intmain(){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(autoval:res)cout<<val<<" ";cout<<endl;return0;}
Java
// Java program to find Diagonal Traversal of a Matriximportjava.util.*;classGfG{// Function that returns elements of given mat in diagonal orderstaticArrayList<Integer>diagonalOrder(int[][]mat){ArrayList<Integer>res=newArrayList<>();intn=mat.length;intm=mat[0].length;// There will be n+m-1 diagonals in totalfor(intline=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 linesintstartCol=Math.max(0,line-n);// Get count of elements in this diagonal// Count equals minimum of line number, (m-startCol) and nintcount=Math.min(Math.min(line,m-startCol),n);// Process elements of this diagonalfor(intj=0;j<count;j++){// Calculate row and column indices // for each element in the diagonalintrow=Math.min(n,line)-j-1;intcol=startCol+j;res.add(mat[row][col]);}}returnres;}publicstaticvoidmain(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(intval: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 orderdefdiagonalOrder(mat):res=[]n=len(mat)m=len(mat[0])# There will be n+m-1 diagonals in totalforlineinrange(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 linesstartCol=max(0,line-n)# Get count of elements in this diagonal# Count equals minimum of line number, (m-startCol) and ncount=min(line,m-startCol,n)# Process elements of this diagonalforjinrange(count):# Calculate row and column indices # for each element in the diagonalrow=min(n,line)-j-1col=startCol+jres.append(mat[row][col])returnresif__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 MatrixusingSystem;usingSystem.Collections.Generic;classGfG{// Function that returns elements of given mat in diagonal orderstaticList<int>diagonalOrder(int[][]mat){List<int>res=newList<int>();intn=mat.Length;intm=mat[0].Length;// There will be n+m-1 diagonals in totalfor(intline=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 linesintstartCol=Math.Max(0,line-n);// Get count of elements in this diagonal// Count equals minimum of line number, (m-startCol) and nintcount=Math.Min(Math.Min(line,m-startCol),n);// Process elements of this diagonalfor(intj=0;j<count;j++){// Calculate row and column indices // for each element in the diagonalintrow=Math.Min(n,line)-j-1;intcol=startCol+j;res.Add(mat[row][col]);}}returnres;}staticvoidMain(string[]args){int[][]mat=newint[][]{newint[]{1,2,3,4},newint[]{5,6,7,8},newint[]{9,10,11,12},newint[]{13,14,15,16},newint[]{17,18,19,20}};List<int>res=diagonalOrder(mat);foreach(intvalinres)Console.Write(val+" ");Console.WriteLine();}}
JavaScript
// JavaScript program to find Diagonal Traversal of a Matrix// Function that returns elements of given mat in diagonal orderfunctiondiagonalOrder(mat){letres=[];letn=mat.length;letm=mat[0].length;// There will be n+m-1 diagonals in totalfor(letline=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 linesletstartCol=Math.max(0,line-n);// Get count of elements in this diagonal// Count equals minimum of line number, (m-startCol) and nletcount=Math.min(line,m-startCol,n);// Process elements of this diagonalfor(letj=0;j<count;j++){// Calculate row and column indices // for each element in the diagonalletrow=Math.min(n,line)-j-1;letcol=startCol+j;res.push(mat[row][col]);}}returnres;}letmat=[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16],[17,18,19,20]];letres=diagonalOrder(mat);console.log(res.join(" "));
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>usingnamespacestd;// Function that returns elements of given mat in diagonal ordervector<int>diagonalOrder(constvector<vector<int>>&mat){vector<int>res;intn=mat.size();intm=mat[0].size();// Process all diagonals starting from the first columnfor(introw=0;row<n;row++){inti=row,j=0;// Follow each diagonal going up and rightwhile(i>=0&&j<m){res.push_back(mat[i][j]);i--;j++;}}// Process remaining diagonals starting from // the bottom row (except first column)for(intcol=1;col<m;col++){inti=n-1,j=col;// Follow each diagonal going up and rightwhile(i>=0&&j<m){res.push_back(mat[i][j]);i--;j++;}}returnres;}intmain(){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(autoval:res)cout<<val<<" ";cout<<endl;return0;}
Java
// Java program to find Diagonal Traversal of a Matriximportjava.util.ArrayList;classGfG{// Function that returns elements of given mat in diagonal orderstaticArrayList<Integer>diagonalOrder(int[][]mat){ArrayList<Integer>res=newArrayList<>();intn=mat.length;intm=mat[0].length;// Process all diagonals starting from the first columnfor(introw=0;row<n;row++){inti=row,j=0;// Follow each diagonal going up and rightwhile(i>=0&&j<m){res.add(mat[i][j]);i--;j++;}}// Process remaining diagonals starting from // the bottom row (except first column)for(intcol=1;col<m;col++){inti=n-1,j=col;// Follow each diagonal going up and rightwhile(i>=0&&j<m){res.add(mat[i][j]);i--;j++;}}returnres;}publicstaticvoidmain(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(intval: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 orderdefdiagonalOrder(mat):res=[]n=len(mat)m=len(mat[0])# Process all diagonals starting from the first columnforrowinrange(n):i=rowj=0# Follow each diagonal going up and rightwhilei>=0andj<m:res.append(mat[i][j])i-=1j+=1# Process remaining diagonals starting from # the bottom row (except first column)forcolinrange(1,m):i=n-1j=col# Follow each diagonal going up and rightwhilei>=0andj<m:res.append(mat[i][j])i-=1j+=1returnresif__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)forvalinres:print(val,end=" ")print()
C#
// C# program to find Diagonal Traversal of a MatrixusingSystem;usingSystem.Collections.Generic;classGfG{// Function that returns elements of given mat in diagonal orderstaticList<int>diagonalOrder(int[,]mat){List<int>res=newList<int>();intn=mat.GetLength(0);intm=mat.GetLength(1);// Process all diagonals starting from the first columnfor(introw=0;row<n;row++){inti=row,j=0;// Follow each diagonal going up and rightwhile(i>=0&&j<m){res.Add(mat[i,j]);i--;j++;}}// Process remaining diagonals starting from // the bottom row (except first column)for(intcol=1;col<m;col++){inti=n-1,j=col;// Follow each diagonal going up and rightwhile(i>=0&&j<m){res.Add(mat[i,j]);i--;j++;}}returnres;}staticvoidMain(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(intvalinres){Console.Write(val+" ");}Console.WriteLine();}}
JavaScript
// JavaScript program to find Diagonal Traversal of a Matrix// Function that returns elements of given mat in diagonal orderfunctiondiagonalOrder(mat){letres=[];letn=mat.length;letm=mat[0].length;// Process all diagonals starting from the first columnfor(letrow=0;row<n;row++){leti=row,j=0;// Follow each diagonal going up and rightwhile(i>=0&&j<m){res.push(mat[i][j]);i--;j++;}}// Process remaining diagonals starting from // the bottom row (except first column)for(letcol=1;col<m;col++){leti=n-1,j=col;// Follow each diagonal going up and rightwhile(i>=0&&j<m){res.push(mat[i][j]);i--;j++;}}returnres;}letmat=[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16],[17,18,19,20]];letres=diagonalOrder(mat);for(letvalofres){process.stdout.write(val+" ");}console.log();