Print matrix in diagonal pattern

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

```Input : mat[3][3] = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}}
Output : 1 2 4 7 5 3 6 8 9.
Explanation: We 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 : mat[4][4] =  {{1,  2,  3,  10},
{4,  5,  6,  11},
{7,  8,  9,  12},
{13, 14, 15, 16}}
Output:  1 2 4 7 5 3 10 6 8 13 14 9 11 12 15 16 .
```

Recommended: Please solve it on “PRACTICE” first, before moving on to the solution.

1. We use a flag isUp to decide whether we need to go upward direction or downward direction. We set isUp = true initially that first we are going upward.
2. If isUp = 1 then start printing elements by incrementing column index and decrementing the row index.
3. Similarly if isUp = 0, then decrement the column index and increment the row index.
4. Do this till all the elements get traversed.

Below is C++ implementation of above steps.

```// C++ program to print matrix in diagonal order
#include <bits/stdc++.h>
using namespace std;
const int MAX = 100;

void printMatrixDiagonal(int mat[MAX][MAX], int n)
{
// Initialize indexes of element to be printed next
int i = 0, j = 0 ;

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

// 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--)
{
cout << 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 = 0 then traverse up to down
else
{
for ( ; j >= 0 && i<n ; i++ , j--)
{
cout << 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 main()
{
int mat[MAX][MAX] = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

int n = 3;
printMatrixDiagonal(mat, n);
return 0;
}
```

Output:

```1 2 4 7 5 3 6 8 9
```

This article is contributed by Sahil Chhabra(KILLER). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.
3.6 Average Difficulty : 3.6/5.0
Based on 18 vote(s)