Given a matrix, the task is to interchange its first and last rows. This can be done by swapping the corresponding elements of the first and last rows.
- Swap each element of the first row with the corresponding element of the last row.
- The operation can be performed in-place using constant extra space.
Example
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
Approach
The first and last rows have the same number of elements. Traverse all columns and swap the corresponding elements of these two rows.
- Traverse each column of the matrix.
- Swap the element at the first row with the element at the last row.
- Print the updated matrix.
#include <iostream>
using namespace std;
const int N = 4;
// Interchange first and last rows
void interchangeFirstLast(int mat[N][N])
{
for (int j = 0; j < N; j++) {
swap(mat[0][j], mat[N - 1][j]);
}
}
int main()
{
int mat[N][N] = {
{8, 9, 7, 6},
{4, 7, 6, 5},
{3, 2, 1, 8},
{9, 9, 7, 7}
};
interchangeFirstLast(mat);
// Print the updated matrix
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
cout << mat[i][j] << " ";
}
cout << '\n';
}
return 0;
}
Output
9 9 7 7 4 7 6 5 3 2 1 8 8 9 7 6
Explanation
- The loop traverses all columns of the matrix.
swap()exchanges the corresponding elements of the first and last rows.- The matrix is modified directly without using another matrix.