📜  交换矩阵对角线的Java程序

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

交换矩阵对角线的Java程序

给定一个 n*n 阶的方阵,你必须交换两条对角线的元素。
例子 :

Input : matrix[][] = {1, 2, 3,
                      4, 5, 6,
                      7, 8, 9} 
Output : matrix[][] = {3, 2, 1,
                       4, 5, 6,
                       9, 8, 7} 

Input : matrix[][] = {4,  2,  3,  1,
                      5,  7,  6,  8,
                      9, 11, 10, 12,
                     16, 14, 15, 13} 
Output : matrix[][] = {1,  2,  3,  4,
                       5,  6,  7,  8,
                       9, 10, 11, 12,
                      11, 14, 15, 16}

解释:交换方阵的对角线背后的想法很简单。从 0 迭代到 n-1,每次迭代都必须交换 a[i][i] 和 a[i][ni-1]。

时间复杂度:O(n)

Java
// Java program to interchange 
// the diagonals of matrix
import java.io.*;
  
class GFG 
{
    public static int N = 3;
      
    // Function to interchange diagonals
    static void interchangeDiagonals(int array[][])
    {
        // swap elements of diagonal
        for (int i = 0; i < N; ++i)
            if (i != N / 2)
            {
                int temp = array[i][i];
                array[i][i] = array[i][N - i - 1];
                array[i][N - i - 1] = temp;
            }
  
        for (int i = 0; i < N; ++i)
        {
            for (int j = 0; j < N; ++j)
                System.out.print(array[i][j]+" ");
            System.out.println();
        }
    }
      
    // Driver Code
    public static void main (String[] args) 
    {
        int array[][] = { {4, 5, 6},
                        {1, 2, 3},
                        {7, 8, 9}
                        };
        interchangeDiagonals(array);
    }
}
  
// This code is contributed by Pramod Kumar


输出:

6 5 4
 1 2 3
 9 8 7

请参阅完整的文章关于交换矩阵对角线的程序以获取更多详细信息!