# Print matrix elements diagonally in spiral form

Given a matrix arr[][] of dimensions N * M and an integer K, the task is to print all elements of the matrix starting from the top-left element up to K diagonally in spiral form.

Examples:

Input : N=5, M=6, K=15, arr[][]={{1, 2, 3, 4, 5, 6},
{7, 8, 9, 10, 11, 12},
{13, 14, 15, 16, 17, 18},
{19, 20, 21, 22, 23, 24},
{25, 26, 27, 28, 29, 30}}
Output: 1, 2, 7, 13, 8, 3, 4, 9, 14, 19, 25, 20, 15
Explanation:

1st diagonal printed: {1}
2nd diagonal printed: {2, 7}
3rd diagonal printed: {13, 8, 3}
……
5th diagonal printed {25, 20, 15}.
Since 15 is encountered, no further matrix element is printed.

Input: N = 4, M = 3, K = 69, arr[][]={{4, 87, 24},
{17, 1, 18},
{25, 69, 97},
{19, 27, 85}}
Output: 4, 87, 17, 25, 1, 24, 18, 69

Approach: Follow the steps below to solve the problem:

1. The total number of diagonals in the matrix is N + M – 1.
2. Traverse the diagonal one by one in spiral manner.
3. For every element traversed, check if it is equal to K or not. If found to be true, print that element and terminate.
4. Otherwise, print the element and evaluate the next indices to be traversed. If i and j are the current indexes:
• While moving diagonally up i will be decremented and j will be incremented.
• While moving diagonally down i will be incremented and j will be decremented.
5. If the next index is not a valid index, then move to the next diagonal.
6. Otherwise, update the current position to the next.

Below is the implementation of the above approach:

 `// C++ program for the above approach ` `#include ` `using` `namespace` `std; `   `// Function to check if the ` `// indices are valid or not ` `bool` `isValid(``int` `i, ``int` `j, ` `            ``int` `N, ``int` `M) ` `{ ` `    ``return` `(i >= 0 && i < N ` `            ``&& j >= 0 && j < M); ` `} `   `// Function to evaluate the next ` `// index while moving diagonally up ` `pair<``int``, ``int``> up(``int` `i, ``int` `j, ` `                ``int` `N, ``int` `M) ` `{ ` `    ``if` `(isValid(i - 1, j + 1, N, M)) ` `        ``return` `{ i - 1, j + 1 }; ` `    ``else` `        ``return` `{ -1, -1 }; ` `} `   `// Function to evaluate the next ` `// index while moving diagonally down ` `pair<``int``, ``int``> down(``int` `i, ``int` `j, ` `                    ``int` `N, ``int` `M) ` `{ ` `    ``if` `(isValid(i + 1, j - 1, N, M)) ` `        ``return` `{ i + 1, j - 1 }; ` `    ``else` `        ``return` `{ -1, -1 }; ` `} `   `// Function to print matrix elements ` `// diagonally in Spiral Form ` `void` `SpiralDiagonal(``int` `N, ``int` `M, ``int` `K, ` `                    ``vector > a) ` `{ ` `    ``int` `i = 0, j = 0; `   `    ``// Total Number of Diagonals ` `    ``// = N + M - 1 ` `    ``for` `(``int` `diagonal = 0; ` `        ``diagonal < N + M - 1; ` `        ``diagonal++) { `   `        ``while` `(1) { `   `            ``// Stop when K is ` `            ``// encountered ` `            ``if` `(a[i][j] == K) { `   `                ``cout << K; ` `                ``return``; ` `            ``} `   `            ``// Print the integer ` `            ``cout << a[i][j] << ``", "``; `   `            ``// Store the next index ` `            ``pair<``int``, ``int``> next; ` `            ``if` `(diagonal & 1) { `   `                ``next = down(i, j, N, M); ` `            ``} ` `            ``else` `{ `   `                ``next = up(i, j, N, M); ` `            ``} `   `            ``// If current index is invalid ` `            ``if` `(next.first == next.second ` `                ``&& next.first == -1) { `   `                ``// Move to the next diagonal ` `                ``if` `(diagonal & 1) { `   `                    ``(i + 1 < N) ? ++i : ++j; ` `                ``} ` `                ``else` `{ `   `                    ``(j + 1 < M) ? ++j : ++i; ` `                ``} ` `                ``break``; ` `            ``} `   `            ``// Otherwise move to the ` `            ``// next valid index ` `            ``else` `{ `   `                ``i = next.first; ` `                ``j = next.second; ` `            ``} ` `        ``} ` `    ``} ` `} `   `// Driver Code ` `int` `main() ` `{ `   `    ``int` `N = 5, M = 6, K = 15; ` `    ``vector > arr ` `        ``= { { 1, 2, 3, 4, 5, 6 }, ` `            ``{ 7, 8, 9, 10, 11, 12 }, ` `            ``{ 13, 14, 15, 16, 17, 18 }, ` `            ``{ 19, 20, 21, 22, 23, 24 }, ` `            ``{ 25, 26, 27, 28, 29, 30 } }; `   `    ``// Function Call ` `    ``SpiralDiagonal(N, M, K, arr); `   `    ``return` `0; ` `}`

 `// Java program for the ` `// above approach` `import` `java.util.*;` `import` `java.lang.*;` ` `  `class` `GFG{` `static` `class` `pair` `{` `    ``int` `first, second;` `    ``pair(``int` `f, ``int` `s)` `    ``{` `        ``this``.first = f;` `        ``this``.second = s;` `    ``}` `}`   `// Function to check if the` `// indices are valid or not` `static` `boolean` `isValid(``int` `i, ``int` `j,` `                       ``int` `N, ``int` `M)` `{` `    ``return` `(i >= ``0` `&& i < N && ` `            ``j >= ``0` `&& j < M);` `}` ` `  `// Function to evaluate the next` `// index while moving diagonally up` `static` `int``[] up(``int` `i, ``int` `j,` `                ``int` `N, ``int` `M)` `{` `    ``if` `(isValid(i - ``1``, j + ``1``, N, M))` `        ``return` `new` `int``[]{ i - ``1``, j + ``1` `};` `    ``else` `        ``return` `new` `int``[]{ -``1``, -``1` `};` `}` ` `  `// Function to evaluate the next` `// index while moving diagonally down` `static` `int``[] down(``int` `i, ``int` `j,` `                  ``int` `N, ``int` `M)` `{` `    ``if` `(isValid(i + ``1``, j - ``1``, N, M))` `        ``return` `new` `int``[]{ i + ``1``, j - ``1` `};` `    ``else` `        ``return` `new` `int``[]{ -``1``, -``1` `};` `}` ` `  `// Function to print matrix elements` `// diagonally in Spiral Form` `static` `void` `SpiralDiagonal(``int` `N, ``int` `M, ` `                           ``int` `K, ``int``[][] a)` `{` `    ``int` `i = ``0``, j = ``0``;` ` `  `    ``// Total Number of Diagonals` `    ``// = N + M - 1` `    ``for``(``int` `diagonal = ``0``;` `            ``diagonal < N + M - ``1``;` `            ``diagonal++)` `    ``{` `        ``while` `(``true``)` `        ``{` `            `  `            ``// Stop when K is` `            ``// encountered` `            ``if` `(a[i][j] == K)` `            ``{` `                ``System.out.print(K);` `                ``return``;` `            ``}` `            `  `            ``// Print the integer` `            ``System.out.print(a[i][j] + ``", "``);` `            `  `            ``// Store the next index` `            ``int``[] next;` `            `  `            ``if` `((diagonal & ``1``) == ``1``)` `            ``{` `                ``next = down(i, j, N, M);` `            ``}` `            ``else` `            ``{` `                ``next = up(i, j, N, M);` `            ``}` ` `  `            ``// If current index is invalid` `            ``if` `(next[``0``] == next[``1``] &&` `                ``next[``1``] == -``1``)` `            ``{` `                `  `                ``// Move to the next diagonal` `                ``if` `((diagonal & ``1``) == ``1``)` `                ``{` `                    ``if` `(i + ``1` `< N)` `                        ``++i;` `                    ``else` `                        ``++j;` `                ``}` `                ``else` `                ``{` `                    ``if` `(j + ``1` `< M)` `                        ``++j;` `                    ``else` `                        ``++i;` `                ``}` `                ``break``;` `            ``}` `            `  `            ``// Otherwise move to the` `            ``// next valid index` `            ``else` `            ``{` `                ``i = next[``0``];` `                ``j = next[``1``];` `            ``}` `        ``}` `    ``}` `}` ` `  `// Driver code` `public` `static` `void` `main (String[] args)` `{` `    ``int` `N = ``5``, M = ``6``, K = ``15``;` `    ``int``[][] arr = { { ``1``, ``2``, ``3``, ``4``, ``5``, ``6` `},` `                    ``{ ``7``, ``8``, ``9``, ``10``, ``11``, ``12` `},` `                    ``{ ``13``, ``14``, ``15``, ``16``, ``17``, ``18` `},` `                    ``{ ``19``, ``20``, ``21``, ``22``, ``23``, ``24` `},` `                    ``{ ``25``, ``26``, ``27``, ``28``, ``29``, ``30` `} };` `                    `  `    ``// Function Call` `    ``SpiralDiagonal(N, M, K, arr);` `}` `}`   `// This code is contributed by offbeat`

Output:

```1, 2, 7, 13, 8, 3, 4, 9, 14, 19, 25, 20, 15
```

Time Complexity: O(N*M)
Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

Student at CMR College of Engineering and Technology (Electronics and Communication)

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.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Improved By : offbeat