Return an array of anti-diagonals of given N*N square matrix

Given a square matrix of size N*N, return an array of its anti-diagonals. For better understanding let us look at the image given below:
Examples: 

Input :

Output :
 1
 2  5
 3  6  9
 4  7  10  13
 8  11 14
 12 15
 16

Approach 1:
To solve the problem mentioned above we have two major observations. 

Below is the implementation of the above approach: 

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP implementation to  return
// an array of its anti-diagonals
// when an N*N square matrix is given
 
#include <iostream>
using namespace std;
 
// function to print the diagonals
void diagonal(int A[3][3])
{
 
    int N = 3;
 
    // For each column start row is 0
    for (int col = 0; col < N; col++) {
 
        int startcol = col, startrow = 0;
 
        while (startcol >= 0 && startrow < N) {
            cout << A[startrow][startcol] << " ";
 
            startcol--;
 
            startrow++;
        }
        cout << "\n";
    }
 
    // For each row start column is N-1
    for (int row = 1; row < N; row++) {
        int startrow = row, startcol = N - 1;
 
        while (startrow < N && startcol >= 0) {
            cout << A[startrow][startcol] << " ";
 
            startcol--;
 
            startrow++;
        }
        cout << "\n";
    }
}
 
// Driver code
int main()
{
 
    // matrix iniliasation
    int A[3][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
 
    diagonal(A);
 
    return 0;
}
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// JAVA implementation to  return
// an array of its anti-diagonals
// when an N*N square matrix is given
 
class Matrix {
 
    // function to print the diagonals
    void diagonal(int A[][])
    {
 
        int N = 3;
 
        // For each column start row is 0
        for (int col = 0; col < N; col++) {
 
            int startcol = col, startrow = 0;
 
            while (startcol >= 0 && startrow < N) {
 
                System.out.print(A[startrow][startcol]
                                 + " ");
 
                startcol--;
 
                startrow++;
            }
            System.out.println();
        }
 
        // For each row start column is N-1
        for (int row = 1; row < N; row++) {
            int startrow = row, startcol = N - 1;
 
            while (startrow < N && startcol >= 0) {
                System.out.print(A[startrow][startcol]
                                 + " ");
 
                startcol--;
 
                startrow++;
            }
            System.out.println();
        }
    }
 
    // Driver code
    public static void main(String args[])
    {
 
        // matrix initialisation
        int A[][]
            = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
 
        Matrix m = new Matrix();
 
        m.diagonal(A);
    }
}
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation to return
# an array of its anti-diagonals
# when an N*N square matrix is given
 
# function to print the diagonals
 
 
def diagonal(A):
 
    N = 3
 
    # For each column start row is 0
    for col in range(N):
 
        startcol = col
        startrow = 0
 
        while(startcol >= 0 and
              startrow < N):
            print(A[startrow][startcol],
                  end=" ")
 
            startcol -= 1
            startrow += 1
 
        print()
 
    # For each row start column is N-1
    for row in range(1, N):
        startrow = row
        startcol = N - 1
 
        while(startrow < N and
              startcol >= 0):
            print(A[startrow][startcol],
                  end=" ")
 
            startcol -= 1
            startrow += 1
 
        print()
 
 
# Driver code
if __name__ == "__main__":
 
    # matrix iniliasation
    A = [[1, 2, 3],
         [4, 5, 6],
         [7, 8, 9]]
 
    diagonal(A)
 
# This code is contributed by AnkitRai01
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation to return
// an array of its anti-diagonals
// when an N*N square matrix is given
using System;
 
class GFG {
 
    // Function to print the diagonals
    static void diagonal(int[, ] A)
    {
        int N = 3;
 
        // For each column start row is 0
        for (int col = 0; col < N; col++) {
            int startcol = col, startrow = 0;
 
            while (startcol >= 0 && startrow < N) {
                Console.Write(A[startrow, startcol] + " ");
                startcol--;
                startrow++;
            }
            Console.WriteLine();
        }
 
        // For each row start column is N-1
        for (int row = 1; row < N; row++) {
            int startrow = row, startcol = N - 1;
 
            while (startrow < N && startcol >= 0) {
                Console.Write(A[startrow, startcol] + " ");
                startcol--;
                startrow++;
            }
            Console.WriteLine();
        }
    }
 
    // Driver code
    public static void Main(string[] args)
    {
 
        // Matrix initialisation
        int[, ] A
            = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
 
        diagonal(A);
    }
}
 
// This code is contributed by AnkitRai01
chevron_right

Output: 

1 
2 4 
3 5 7 
6 8 
9






 

Time Complexity: Time complexity of the above solution is O(N*N).

Approach 2 : Much simpler and concise  ( Same time Complexity)

In this approach we will make the use of sum of indices of any element in a matrix.   Let indices of any element be represented by i (row) an j (column).

If we find the sum of indices of any element in  a N*N matrix, we will observe that the sum of indices for any element lies between 0 (when i = j = 0) and 2*N – 2 (when i = j = N-1). 

So we will follow the following steps:

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program for the above approach
#include <iostream>
#include <vector>
using namespace std;
 
// Function to print diagonals
void diagonal(vector<vector<int> >& A)
{
 
    int n = A.size();
    int N = 2 * n - 1;
 
    vector<vector<int> > result(N);
 
    // Push each element in the result vector
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++)
            result[i + j].push_back(A[i][j]);
   
    // Print the diagonals
    for (int i = 0; i < result.size(); i++)
    {
        cout << endl;
        for (int j = 0; j < result[i].size(); j++)
            cout << result[i][j] << " ";
    }
}
 
// Driver Code
int main()
{
 
    vector<vector<int> > A = { { 1, 2, 3, 4 },
                               { 5, 6, 7, 8 },
                               { 9, 10, 11, 12 },
                               { 13, 14, 15, 16 } };
     
    // Function Call
    diagonal(A);
 
    return 0;
}
chevron_right

Output : 

1  
2 5  
3 6 9  
4 7 10 13  
8 11 14  
12 15  
16 

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





Check out this Author's contributed articles.

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.



Article Tags :