ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、视频、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
# 矩阵中第一行和最后一行的交换元素 > 原文: [https://www.geeksforgeeks.org/interchange-elements-of-first-and-last-rows-in-matrix/](https://www.geeksforgeeks.org/interchange-elements-of-first-and-last-rows-in-matrix/) 给定 4 x 4 矩阵,我们必须交换第一行和最后一行的元素,并显示结果矩阵。 **示例**: ``` Input : 3 4 5 0 2 6 1 2 2 7 1 2 2 1 1 2 Output : 2 1 1 2 2 6 1 2 2 7 1 2 3 4 5 0 Input : 9 7 5 1 2 3 4 1 5 6 6 5 1 2 3 1 Output : 1 2 3 1 2 3 4 1 5 6 6 5 9 7 5 1 ``` 该方法非常简单,我们可以简单地交换矩阵第一行和最后一行的元素,以获取所需的矩阵作为输出。 下面是该方法的实现: ## C++ ```cpp // C++ code to swap the element of first // and last row and display the result #include <iostream> using namespace std; #define n 4 void interchangeFirstLast(int m[][n]) {         int rows = n;         // swapping of element between first         // and last rows         for (int i = 0; i < n; i++)         {             int t = m[0][i];             m[0][i] = m[rows - 1][i];             m[rows - 1][i] = t;         } }  // Driver function int main() {     // input in the array     int m[n][n] = { { 8, 9, 7, 6 },                 { 4, 7, 6, 5 },                 { 3, 2, 1, 8 },                 { 9, 9, 7, 7 } };      interchangeFirstLast(m);      // printing the interchanged matrix     for (int i = 0; i < n; i++)     {         for (int j = 0; j < n; j++)              cout << m[i][j] << " ";         cout << endl;     } } // This code is contributed by Anant Agarwal. ```