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.
Examples :
Input 1 : 1 1 5 0
2 3 7 2
8 9 1 3
6 7 8 2
Output 1 : 0 1 5 1
2 3 7 2
3 9 1 8
2 7 8 6
Input 2 : 7 8 9 10
11 13 14 1
15 7 12 22
11 21 30 1
Output 2 : 10 8 9 7
1 13 14 11
22 7 12 15
1 21 30 11
Approach:
To get the required output, we need to swap the elements of the first and last column of the stated matrix.
Example
Java
import java.io.*;
class GFG {
static int N = 3 ;
static void Swap_First_Last( int mat[][])
{
int cls = N;
for ( int j = 0 ; j < N; j++) {
int temp = mat[j][ 0 ];
mat[j][ 0 ] = mat[j][N - 1 ];
mat[j][N - 1 ] = temp;
}
}
public static void main(String[] args)
{
int mat[][]
= { { 1 , 2 , 3 }, { 4 , 5 , 6 }, { 7 , 8 , 9 } };
for ( int j = 0 ; j < N; j++) {
for ( int k = 0 ; k < N; k++) {
System.out.print(mat[j][k] + " " );
}
System.out.println();
}
System.out.println( "Swapped Matrix as follows : " );
Swap_First_Last(mat);
for ( int j = 0 ; j < N; j++) {
for ( int k = 0 ; k < N; k++)
System.out.print(mat[j][k] + " " );
System.out.println();
}
}
}
|
Output
1 2 3
4 5 6
7 8 9
Swapped Matrix as follows :
3 2 1
6 5 4
9 8 7
Time Complexity: O(N2)
Auxiliary Space: O(1)
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
19 Jul, 2022
Like Article
Save Article