原文:
给定大小为 n * n 的正方形矩阵 mat[][] 。任务是打印位于给定矩阵的超对角线上的所有元素。 例:
输入: mat[][] = { {1,2,3}, {3,3,4,}, {2,4,6}} 输出:2 4 t9】输入: mat[][] = { {1,2,3,4}, {3,3,4,4}, {2,4,6,3}, {1
方法:正方形矩阵的超对角线是位于构成主对角线的元素正上方的元素集。对于主对角线元素,它们的索引类似于(i = j),对于超对角线元素,它们的索引为 j = i 1 (i 表示行,j 表示列)。 因此元素 arr[0][1],arr[1][2],arr[2][3],arr[3][4],…。是超对角线的元素。 遍历矩阵的所有元素,只打印 j = i 1 的元素,这需要 o(n 2 )的时间复杂度,或者只遍历从 1 到列 count–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
python 3
# 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 */
java 描述语言
output:
2 7 12
麻将胡了pg电子网站的版权属于:月萌api www.moonapi.com,转载请注明出处