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

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

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

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

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

C++
// C++ implementation of the approach
#include 
using namespace std;
#define R 4
#define C 4
 
// Function to print the sub diagonal
// elements of the given matrix
void printSubDiagonal(int arr[R][C])
{
    for (int i = 1; i < R; i++) {
        cout << arr[i][i - 1] << " ";
    }
}
 
// Driver code
int main()
{
    int arr[R][C] = { { 1, 2, 3, 4 },
                      { 5, 6, 7, 8 },
                      { 9, 10, 11, 12 },
                      { 13, 14, 15, 16 } };
 
    printSubDiagonal(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 < R; i++)
    {
            System.out.print(arr[i][i - 1] + " ");
    }
}
 
// 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 ajit.


Python3
# Python3 implementation of the approach
R = 4
C = 4
 
# Function to print the sub diagonal
# elements of the given matrix
def printSubDiagonal(arr):
 
    for i in range(1, R):
        print(arr[i][i - 1], end = " ")
 
# Driver code
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


C#
// C# implementation of the approach
using System;
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 < R; i++)
        {
                Console.Write(arr[i, i - 1] + " ");
        }
    }
     
    // Driver code
    public static void Main ()
    {
        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 CodeMech.


Javascript


输出:
5 10 15

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