给定方阵,交换主要和次要对角线元素。
Major Diagonal Elements of a Matrix :
The Major Diagonal Elements are the ones that occur from Top Left of Matrix Down To Bottom Right Corner. The Major Diagonal is also known as Main Diagonal or Primary Diagonal.
Minor Diagonal Elements of a Matrix :
The Minor Diagonal Elements are the ones that occur from Top Right of Matrix Down To Bottom Left Corner. Also known as Secondary Diagonal.
例子 :
Input : 0 1 2
3 4 5
6 7 8
Output : 2 1 0
3 4 5
8 7 6
方法 :
一个简单的事情应该知道,主要或主要对角线的索引是相同的,即假设A是矩阵,那么A [1] [1]将是主要对角线元素,次要对角线的索引和等于矩阵的大小。假设A是大小为3的矩阵,那么A [1] [2]将是次对角元素。
下面是上述方法的实现:
C++
// CPP Program to swap diagonal of a matrix
#include
using namespace std;
// size of square matrix
#define N 3
// Function to swap diagonal of matrix
void swapDiagonal(int matrix[][N]) {
for (int i = 0; i < N; i++)
swap(matrix[i][i], matrix[i][N - i - 1]);
}
// Driver Code
int main() {
int matrix[N][N] = {{0, 1, 2},
{3, 4, 5},
{6, 7, 8}};
swapDiagonal(matrix);
// Displaying modified matrix
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
cout << matrix[i][j] << " ";
cout << endl;
}
return 0;
}
Java
// Java implementation to swap
// diagonal of a matrix
import java.io.*;
class Gfg {
static int N = 3;
// Function to swap diagonal of matrix
static void swapDiagonal(int matrix[][]) {
for (int i = 0; i < N; i++) {
int temp = matrix[i][i];
matrix[i][i] = matrix[i][N - i - 1];
matrix[i][N - i - 1] = temp;
}
}
// Driver function
public static void main(String arg[]) {
int matrix[][] = {{0, 1, 2},
{3, 4, 5},
{6, 7, 8}};
swapDiagonal(matrix);
// Displaying modified matrix
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
System.out.print(matrix[i][j] + " ");
System.out.println();
}
}
}
// This code is contributed by Anant Agarwal.
Python3
# Python3 Program to swap diagonal of a matrix
# size of square matrix
N = 3
# Function to swap diagonal of matrix
def swapDiagonal(matrix):
for i in range(N):
matrix[i][i], matrix[i][N-i-1] = \
matrix[i][N-i-1], matrix[i][i]
# Driver Code
matrix = [[0, 1, 2],
[3, 4, 5],
[6, 7, 8]]
# swap diagonals of matrix
swapDiagonal(matrix);
# Displaying modified matrix
for i in range(N):
for j in range(N):
print(matrix[i][j], end = ' ')
print()
C#
// C# implementation to swap
// diagonal of a matrix
using System;
class Gfg {
static int N = 3;
// Function to swap diagonal of matrix
static void swapDiagonal(int [,]matrix) {
for (int i = 0; i < N; i++) {
int temp = matrix[i,i];
matrix[i,i] = matrix[i,N - i - 1];
matrix[i,N - i - 1] = temp;
}
}
// Driver function
public static void Main() {
int [,]matrix = {{0, 1, 2},
{3, 4, 5},
{6, 7, 8}};
swapDiagonal(matrix);
// Displaying modified matrix
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
Console.Write(matrix[i,j] + " ");
Console.WriteLine();
}
}
}
// This code is contributed by vt_m.
PHP
Javascript
输出 :
2 1 0
3 4 5
8 7 6