📜  返回给定N * N方阵的反对角数组

📅  最后修改于: 2021-04-22 00:36:21             🧑  作者: Mango

给定大小为N * N的方阵,返回其反对角线数组。为了更好地理解,让我们看下面的图像:

例子:

Input :

空值

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

方法1:
为了解决上述问题,我们有两个主要观察结果。

  • 第一个是,某些对角线从每列的第零行开始,并在开始列> = 0或开始行
  • 第二个观察结果是,其余对角线从每一行的结束列开始,并在开始行 = 0时结束。

下面是上述方法的实现:

C++
// C++ implementation to  return
// an array of its anti-diagonals
// when an N*N square matrix is given
 
#include 
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;
}


Java
// 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);
    }
}


Python3
# 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


C#
// 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


Javascript


C++
// C++ program for the above approach
#include 
#include 
using namespace std;
 
// Function to print diagonals
void diagonal(vector >& A)
{
 
    int n = A.size();
    int N = 2 * n - 1;
 
    vector > 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 > A = { { 1, 2, 3, 4 },
                               { 5, 6, 7, 8 },
                               { 9, 10, 11, 12 },
                               { 13, 14, 15, 16 } };
     
    // Function Call
    diagonal(A);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
import java.lang.*;
 
class GFG{
  
// Function to print diagonals
static void diagonal(int[][] A)
{
    int n = A.length;
    int N = 2 * n - 1;
  
    ArrayList> result = new ArrayList<>();
     
    for(int i = 0; i < N; i++)
        result.add(new ArrayList<>());
  
    // Push each element in the result vector
    for(int i = 0; i < n; i++)
        for(int j = 0; j < n; j++)
            result.get(i + j).add(A[i][j]);
    
    // Print the diagonals
    for(int i = 0; i < result.size(); i++)
    {
        System.out.println();
        for(int j = 0; j < result.get(i).size(); j++)
            System.out.print(result.get(i).get(j) + " ");
    }
}
   
// Driver code
public static void main(String[] args)
{
    int[][] A = { { 1, 2, 3, 4 },
                  { 5, 6, 7, 8 },
                  { 9, 10, 11, 12 },
                  { 13, 14, 15, 16 } };
      
    // Function Call
    diagonal(A);
}
}
 
// This code is contributed by offbeat


Python3
# Python3 program for the above approach
 
# Function to print diagonals
def diagonal(A) :
 
    n = len(A)
    N = 2 * n - 1
 
    result = []
     
    for i in range(N) :
        result.append([])
     
    # Push each element in the result vector
    for i in range(n) :
        for j in range(n) :
            result[i + j].append(A[i][j])
 
    # Print the diagonals
    for i in range(len(result)) :
     
        for j in range(len(result[i])) :
            print(result[i][j] , end = " ")
             
        print()
 
A = [ [ 1, 2, 3, 4 ],
        [ 5, 6, 7, 8 ],
        [ 9, 10, 11, 12 ],
        [ 13, 14, 15, 16 ] ]
 
# Function Call
diagonal(A)
 
# This code is contributed by divyesh072019


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG {
     
    // Function to print diagonals
    static void diagonal(List> A)
    {
      
        int n = A.Count;
        int N = 2 * n - 1;
      
        List> result = new List>();
         
        for (int i = 0; i < N; i++)
        {
            result.Add(new List());
        }
      
        // Push each element in the result vector
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
                result[i + j].Add(A[i][j]);
        
        // Print the diagonals
        for (int i = 0; i < result.Count; i++)
        {
            for (int j = 0; j < result[i].Count; j++)
                Console.Write(result[i][j] + " ");
            Console.WriteLine();
        }
    }
     
  static void Main() {
    List> A = new List>();
    A.Add(new List {1, 2, 3, 4});
    A.Add(new List {5, 6, 7, 8});
    A.Add(new List {9, 10, 11, 12});
    A.Add(new List {13, 14, 15, 16});
       
    // Function Call
    diagonal(A);
  }
}


输出:
1 
2 4 
3 5 7 
6 8 
9

时间复杂度:上述解决方案的时间复杂度为O(N * N)。

方法2:更简单明了(同时复杂度)

在这种方法中,我们将利用矩阵中任何元素的索引和。让任何元素的索引都由i(行)和j(列)表示。

如果找到N * N矩阵中任何元素的索引和,我们将观察到任何元素的索引和都在0(当i = j = 0时)和2 * N – 2(当i = j时)之间= N-1)。

因此,我们将按照以下步骤操作:

  • 声明一个大小为2 * N – 1的向量的向量,以保存从sum = 0到sum = 2 * N – 2的唯一和。
  • 现在,我们将遍历向量,并将类似总和的元素推回向量的该向量中的同一行。

下面是上述方法的实现:

C++

// C++ program for the above approach
#include 
#include 
using namespace std;
 
// Function to print diagonals
void diagonal(vector >& A)
{
 
    int n = A.size();
    int N = 2 * n - 1;
 
    vector > 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 > A = { { 1, 2, 3, 4 },
                               { 5, 6, 7, 8 },
                               { 9, 10, 11, 12 },
                               { 13, 14, 15, 16 } };
     
    // Function Call
    diagonal(A);
 
    return 0;
}

Java

// Java program for the above approach
import java.util.*;
import java.lang.*;
 
class GFG{
  
// Function to print diagonals
static void diagonal(int[][] A)
{
    int n = A.length;
    int N = 2 * n - 1;
  
    ArrayList> result = new ArrayList<>();
     
    for(int i = 0; i < N; i++)
        result.add(new ArrayList<>());
  
    // Push each element in the result vector
    for(int i = 0; i < n; i++)
        for(int j = 0; j < n; j++)
            result.get(i + j).add(A[i][j]);
    
    // Print the diagonals
    for(int i = 0; i < result.size(); i++)
    {
        System.out.println();
        for(int j = 0; j < result.get(i).size(); j++)
            System.out.print(result.get(i).get(j) + " ");
    }
}
   
// Driver code
public static void main(String[] args)
{
    int[][] A = { { 1, 2, 3, 4 },
                  { 5, 6, 7, 8 },
                  { 9, 10, 11, 12 },
                  { 13, 14, 15, 16 } };
      
    // Function Call
    diagonal(A);
}
}
 
// This code is contributed by offbeat

Python3

# Python3 program for the above approach
 
# Function to print diagonals
def diagonal(A) :
 
    n = len(A)
    N = 2 * n - 1
 
    result = []
     
    for i in range(N) :
        result.append([])
     
    # Push each element in the result vector
    for i in range(n) :
        for j in range(n) :
            result[i + j].append(A[i][j])
 
    # Print the diagonals
    for i in range(len(result)) :
     
        for j in range(len(result[i])) :
            print(result[i][j] , end = " ")
             
        print()
 
A = [ [ 1, 2, 3, 4 ],
        [ 5, 6, 7, 8 ],
        [ 9, 10, 11, 12 ],
        [ 13, 14, 15, 16 ] ]
 
# Function Call
diagonal(A)
 
# This code is contributed by divyesh072019

C#

// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG {
     
    // Function to print diagonals
    static void diagonal(List> A)
    {
      
        int n = A.Count;
        int N = 2 * n - 1;
      
        List> result = new List>();
         
        for (int i = 0; i < N; i++)
        {
            result.Add(new List());
        }
      
        // Push each element in the result vector
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
                result[i + j].Add(A[i][j]);
        
        // Print the diagonals
        for (int i = 0; i < result.Count; i++)
        {
            for (int j = 0; j < result[i].Count; j++)
                Console.Write(result[i][j] + " ");
            Console.WriteLine();
        }
    }
     
  static void Main() {
    List> A = new List>();
    A.Add(new List {1, 2, 3, 4});
    A.Add(new List {5, 6, 7, 8});
    A.Add(new List {9, 10, 11, 12});
    A.Add(new List {13, 14, 15, 16});
       
    // Function Call
    diagonal(A);
  }
}

输出 :

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