Given a matrix, the task is to interchange its first and last columns while keeping all other elements unchanged. For each row, the element in the first column is swapped with the corresponding element in the last column. The operation can be performed in-place without creating another matrix.
- The first column has index 0.
- The last column has index cols - 1.
- Traverse the matrix row by row.
Example
Input Matrix:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Output Matrix:
4 2 3 1
8 6 7 5
12 10 11 9
16 14 15 13
Approach
- Store the number of rows and columns of the matrix.
- Traverse each row of the matrix.
- For every row, swap the elements at the first column (0) and last column (cols - 1).
- Use a temporary variable to perform the swap safely.
- Print the updated matrix.
public class GFG {
// Method to swap first and last columns
static void swapFirstLastColumns(int[][] mat) {
int rows = mat.length;
int cols = mat[0].length;
for (int i = 0; i < rows; i++) {
int temp = mat[i][0];
mat[i][0] = mat[i][cols - 1];
mat[i][cols - 1] = temp;
}
}
// Method to print the matrix
static void printMatrix(int[][] mat) {
for (int[] row : mat) {
for (int value : row) {
System.out.print(value + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
int[][] mat = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}
};
swapFirstLastColumns(mat);
System.out.println("Matrix after swapping first and last columns:");
printMatrix(mat);
}
}
Output
Matrix after swapping first and last columns: 4 2 3 1 8 6 7 5 12 10 11 9 16 14 15 13
Explanation:
- mat[i][0] represents the first column element of row i.
- mat[i][cols - 1] represents the last column element.
- These two elements are swapped for every row.
- The matrix is modified in-place, so no additional matrix is required.