原文:

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

输入: mat[][] = { {1,2,3}, {3,3,4,}, {2,4,6}} 输出:3 4 t9】输入: mat[][] = { {1,2,3,4}, {3,3,4,4}, {2,4,6,3}, {1

方法:正方形矩阵的次对角线是位于构成主对角线的元素正下方的元素集。对于主对角线元素,它们的索引类似于(i = j),对于次对角线元素,它们的索引类似于 i = j 1 (i 表示行,j 表示列)。 因此元素 arr[1][0],arr[2][1],arr[3][2],arr[4][3],…。是亚对角线的元素。 要么遍历矩阵的所有元素,只打印 i = j 1 的那些需要 o(n 2 )时间复杂度的元素,要么只打印从 1 到 row count–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.

python 3

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

java 描述语言


output: 

5 10 15