Given a matrix of n*n size, the task is to print its elements in a diagonal pattern.
Input:
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:
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
[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>usingnamespacestd;vector<int>matrixDiagonally(vector<vector<int>>&mat){intn=mat.size();// Initialize indexes of element to be printed nextinti=0,j=0;// Direction is initially from down to upboolisUp=true;vector<int>ans;// Traverse the matrix till all elements get traversedfor(intk=0;k<n*n;){// If isUp = true then traverse from downward to upwardif(isUp){for(;i>=0&&j<n;j++,i--){ans.push_back(mat[i][j]);k++;}// Set i and j according to directionif(i<0&&j<=n-1)i=0;if(j==n)i=i+2,j--;}// If isUp = false then traverse up to downelse{for(;j>=0&&i<n;i++,j--){ans.push_back(mat[i][j]);k++;}// Set i and j according to directionif(j<0&&i<=n-1)j=0;if(i==n)j=j+2,i--;}// Revert the isUp to change the directionisUp=!isUp;}returnans;}// Driver codeintmain(){vector<vector<int>>mat={{1,2,3},{4,5,6},{7,8,9}};vector<int>res=matrixDiagonally(mat);for(intx:res)cout<<x<<" ";return0;}
Java
importjava.util.*;classGFG{staticint[]matrixDiagonally(int[][]mat){intn=mat.length;// Initialize indexes of element to be printed nextinti=0,j=0;// Direction is initially from down to upbooleanisUp=true;ArrayList<Integer>list=newArrayList<>();// Traverse the matrix till all elements get traversedfor(intk=0;k<n*n;){// If isUp = true then traverse from downward to upwardif(isUp){for(;i>=0&&j<n;j++,i--){list.add(mat[i][j]);k++;}// Set i and j according to directionif(i<0&&j<=n-1)i=0;if(j==n){i=i+2;j--;}}// If isUp = false then traverse up to downelse{for(;j>=0&&i<n;i++,j--){list.add(mat[i][j]);k++;}// Set i and j according to directionif(j<0&&i<=n-1)j=0;if(i==n){j=j+2;i--;}}// Revert the isUp to change the directionisUp=!isUp;}int[]ans=newint[list.size()];for(intx=0;x<list.size();x++){ans[x]=list.get(x);}returnans;}}
Python
defmatrixDiagonally(mat):n=len(mat)# Initialize indexes of element to be printed nexti,j=0,0# Direction is initially from down to upisUp=Trueans=[]# Traverse the matrix till all elements get traversedk=0whilek<n*n:# If isUp = true then traverse from downward to upwardifisUp:whilei>=0andj<n:ans.append(mat[i][j])k+=1j+=1i-=1# Set i and j according to directionifi<0andj<=n-1:i=0ifj==n:i=i+2j-=1# If isUp = false then traverse up to downelse:whilej>=0andi<n:ans.append(mat[i][j])k+=1i+=1j-=1# Set i and j according to directionifj<0andi<=n-1:j=0ifi==n:j=j+2i-=1# Revert the isUp to change the directionisUp=notisUpreturnans# Driver codemat=[[1,2,3],[4,5,6],[7,8,9]]res=matrixDiagonally(mat)print(*res)
C#
usingSystem;usingSystem.Collections.Generic;classSolution{publicint[]MatrixDiagonally(int[,]mat){intn=mat.GetLength(0);// Initialize indexes of element to be printed nextinti=0,j=0;// Direction is initially from down to upboolisUp=true;List<int>list=newList<int>();intk=0;// Traverse the matrix till all elements get traversedwhile(k<n*n){// If isUp = true then traverse from downward to upwardif(isUp){while(i>=0&&j<n){list.Add(mat[i,j]);k++;j++;i--;}// Set i and j according to directionif(i<0&&j<=n-1)i=0;if(j==n){i=i+2;j--;}}// If isUp = false then traverse up to downelse{while(j>=0&&i<n){list.Add(mat[i,j]);k++;i++;j--;}// Set i and j according to directionif(j<0&&i<=n-1)j=0;if(i==n){j=j+2;i--;}}// Revert the isUp to change the directionisUp=!isUp;}returnlist.ToArray();// Convert List → int[]}}
JavaScript
functionmatrixDiagonally(mat){letn=mat.length;// Initialize indexes of element to be printed nextleti=0,j=0;// Direction is initially from down to upletisUp=true;letans=[];letk=0;// Traverse the matrix till all elements get traversedwhile(k<n*n){// If isUp = true then traverse from downward to upwardif(isUp){while(i>=0&&j<n){ans.push(mat[i][j]);k++;j++;i--;}// Set i and j according to directionif(i<0&&j<=n-1)i=0;if(j===n){i=i+2;j--;}}// If isUp = false then traverse up to downelse{while(j>=0&&i<n){ans.push(mat[i][j]);k++;i++;j--;}// Set i and j according to directionif(j<0&&i<=n-1)j=0;if(i===n){j=j+2;i--;}}// Revert the isUp to change the directionisUp=!isUp;}returnans;}// Driver codeletmat=[[1,2,3],[4,5,6],[7,8,9]];letres=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>usingnamespacestd;vector<int>matrixDiagonally(vector<vector<int>>&mat){intn=mat.size();// mode - switch to derive up/down traversal// it - iterator count - increases until it// reaches n and then decreasesintmode=0,it=0,lower=0;vector<int>ans;// 2n-1 will be the number of diagonalsfor(intt=0;t<(2*n-1);t++){intt1=t;if(t1>=n){mode++;t1=n-1;it--;lower++;}else{lower=0;it++;}for(inti=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]);}}}returnans;}// Driver codeintmain(){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(intx:res)cout<<x<<" ";return0;}
Java
// C++ program to print matrix in diagonal order#include<bits/stdc++.h>usingnamespacestd;vector<int>matrixDiagonally(vector<vector<int>>&mat){intn=mat.size();// mode - switch to derive up/down traversal// it - iterator count - increases until it// reaches n and then decreasesintmode=0,it=0,lower=0;vector<int>ans;// 2n-1 will be the number of diagonalsfor(intt=0;t<(2*n-1);t++){intt1=t;if(t1>=n){mode++;t1=n-1;it--;lower++;}else{lower=0;it++;}for(inti=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]);}}}returnans;}// Driver codeintmain(){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(intx:res)cout<<x<<" ";return0;}
Python
defmatrixDiagonally(mat):n=len(mat)# mode - switch to derive up/down traversal# it - iterator count - increases until it# reaches n and then decreasesmode=0it=0lower=0ans=[]# 2n-1 will be the number of diagonalsfortinrange(2*n-1):t1=tift1>=n:mode+=1t1=n-1it-=1lower+=1else:lower=0it+=1foriinrange(t1,lower-1,-1):if(t1+mode)%2==0:ans.append(mat[i][t1+lower-i])else:ans.append(mat[t1+lower-i][i])returnans# Driver codemat=[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]res=matrixDiagonally(mat)print(*res)
C#
usingSystem;usingSystem.Collections.Generic;classSolution{publicint[]MatrixDiagonally(int[,]mat){intn=mat.GetLength(0);// mode - switch to derive up/down traversal// it - iterator count - increases until it// reaches n and then decreasesintmode=0,it=0,lower=0;List<int>list=newList<int>();// 2n-1 will be the number of diagonalsfor(intt=0;t<(2*n-1);t++){intt1=t;if(t1>=n){mode++;t1=n-1;it--;lower++;}else{lower=0;it++;}for(inti=t1;i>=lower;i--){if((t1+mode)%2==0){list.Add(mat[i,t1+lower-i]);}else{list.Add(mat[t1+lower-i,i]);}}}returnlist.ToArray();}}
JavaScript
functionmatrixDiagonally(mat){letn=mat.length;// mode - switch to derive up/down traversal// it - iterator count - increases until it// reaches n and then decreasesletmode=0,it=0,lower=0;letans=[];// 2n-1 will be the number of diagonalsfor(lett=0;t<(2*n-1);t++){lett1=t;if(t1>=n){mode++;t1=n-1;it--;lower++;}else{lower=0;it++;}for(leti=t1;i>=lower;i--){if((t1+mode)%2===0){ans.push(mat[i][t1+lower-i]);}else{ans.push(mat[t1+lower-i][i]);}}}returnans;}// Driver codeletmat=[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]];letres=matrixDiagonally(mat);console.log(res.join(" "));