📜  打印给定方阵的所有超对角元素

📅  最后修改于: 2022-05-13 01:57:23.880000             🧑  作者: Mango

打印给定方阵的所有超对角元素

给定一个大小为n * n 的方阵mat[][] 。任务是打印位于给定矩阵的超对角线上的所有元素。
例子:

方法:方阵的超对角线是位于构成主对角线的元素正上方的一组元素。对于主对角元素,它们的索引为 (i = j),对于超对角元素,它们的索引为 j = i + 1(i 表示行,j 表示列)。
因此元素arr[0][1], arr[1][2], arr[2][3], arr[3][4], ....是超对角线的元素。
要么遍历矩阵的所有元素,只打印那些需要 O(n 2 ) 时间复杂度的 j = i + 1 的元素,要么只遍历从 1 到 columnCount – 1 的列并将元素打印为 arr[column – 1][column]。
下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
#define R 4
#define C 4
 
// Function to print the super diagonal
// elements of the given matrix
void printSuperDiagonal(int arr[R][C])
{
    for (int i = 1; i < C; i++) {
        cout << arr[i - 1][i] << " ";
    }
}
 
// Driver code
int main()
{
    int arr[R][C] = { { 1, 2, 3, 4 },
                      { 5, 6, 7, 8 },
                      { 9, 10, 11, 12 },
                      { 13, 14, 15, 16 } };
 
    printSuperDiagonal(arr);
 
    return 0;
}


Java
// Java implementation of the approach
import java.io.*;
 
class GFG
{
     
static int R = 4;
static int C = 4;
 
// Function to print the sub diagonal
// elements of the given matrix
static void printSubDiagonal(int arr[][])
{
    for (int i = 1; i < C; i++)
    {
            System.out.print(arr[i-1][i] + " ");
    }
}
 
// Driver code
public static void main (String[] args)
{
 
    int arr[][] = { { 1, 2, 3, 4 },
                    { 5, 6, 7, 8 },
                    { 9, 10, 11, 12 },
                    { 13, 14, 15, 16 } };
 
    printSubDiagonal(arr);
 
}
}
 
// This code is contributed by mohit kumar 29


Python3
# Python3 implementation of the approach
 
R = 4
C = 4
 
# Function to print the super diagonal
# elements of the given matrix
def printSuperDiagonal(arr) :
 
    for i in range(1, C) :
        print(arr[i - 1][i],end= " ");
 
# Driver code
if __name__ == "__main__" :
     
    arr = [ [ 1, 2, 3, 4 ],
            [5, 6, 7, 8 ],
            [ 9, 10, 11, 12 ],
            [ 13, 14, 15, 16 ]]
    printSuperDiagonal(arr);
     
# This code is contributed by AnkitRai01


C#
// C# implementation of the approach
using System;
     
lass GFG
{
 
    static int R = 4;
    static int C = 4;
 
    // Function to print the sub diagonal
    // elements of the given matrix
    static void printSubDiagonal(int [,]arr)
    {
        for (int i = 1; i < C; i++)
        {
                Console.Write(arr[i-1,i] + " ");
        }
    }
 
    // Driver code
    public static void Main (String[] args)
    {
 
        int [,]arr = { { 1, 2, 3, 4 },
                        { 5, 6, 7, 8 },
                        { 9, 10, 11, 12 },
                        { 13, 14, 15, 16 } };
 
        printSubDiagonal(arr);
    }
}
 
/* This code is contributed by PrinciRaj1992 */


Javascript


输出:
2 7 12

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程