Java Program to Interchange Elements of First and Last in a Matrix Across Columns
Last Updated :
22 Oct, 2024
Improve
For a given 4 x 4 matrix, the task is to interchange the elements of the first and last columns and then return the resultant matrix.
Example Test Case for the Problem
Input : 1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Output : 4 2 3 1
8 6 7 5
12 10 11 9
16 14 15 13
Implementation of Interchange Elements of First and Last in a Matrix Across Columns
// Java Program to Interchange Elements of the
// First and Last Column in a Matrix
// Importing input output classes
import java.io.*;
class GFG {
// Declare static variable and initialize to
// order of the matrix
static int N = 4;
// Method 1
// To swap first and last column in a matrix
static void Swap_First_Last(int mat[][])
{
int cls = N;
// Interchanging of elements between the
// first and last columns
for (int j = 0; j < N; j++) {
int temp = mat[j][0];
mat[j][0] = mat[j][N - 1];
mat[j][N - 1] = temp;
}
}
// Method 2
// Main driver method
public static void main(String[] args)
{
// Creating 2D integer element matrix
// Custom input matrix
int mat[][]
= { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16}};
// Now, calling the (Method1) to interchange
// first and last columns in above matrix
Swap_First_Last(mat);
// Now simply print the updated matrix
// Swapped matrix using nested for loops
// Outer loop for rows
for (int j = 0; j < N; j++) {
// Inner loop for columns
for (int k = 0; k < N; k++)
// Print the swapped matrix
System.out.print(mat[j][k] + " ");
// Operations over a row is computed so new line
System.out.println();
}
}
}
Output
4 2 3 1 8 6 7 5 12 10 11 9 16 14 15 13
Below is the Explanation of the Method:
To get the required output, we need to swap the elements of the first and last column of the stated matrix.
Complexity of the above Method:
Time Complexity: O(N2)
Auxiliary Space: O(1)