💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# 矩阵对角线互换程序 > 原文: [https://www.geeksforgeeks.org/program-to-interchange-diagonals-of-matrix/](https://www.geeksforgeeks.org/program-to-interchange-diagonals-of-matrix/) 给定 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] [n-i-1]。 ![](https://img.kancloud.cn/c8/2a/c82a7550e9b3a671448873e3007a07a0_732x445.png) 时间复杂度:`O(n)` ## C ``` // C program to interchange  // the diagonals of matrix #include<bits/stdc++.h> using namespace std; #define N 3 // Function to interchange diagonals void interchangeDiagonals(int array[][N]) {     // swap elements of diagonal     for (int i = 0; i < N; ++i)     if (i != N / 2)     swap(array[i][i], array[i][N - i - 1]);     for (int i = 0; i < N; ++i)     {     for (int j = 0; j < N; ++j)             printf(" %d", array[i][j]);     printf("\n");     } } // Driver Code int main() {     int array[N][N] = {4, 5, 6,                     1, 2, 3,                     7, 8, 9};     interchangeDiagonals(array);     return 0; } ```