For a given 4 × 4 matrix, the task is to interchange the elements of the first and last rows and then return the resultant matrix.
Illustration:
Input 1: 1 1 5 0
2 3 7 2
8 9 1 3
6 7 8 2
Output 1: 6 7 8 2
2 3 7 2
8 9 1 3
1 1 5 0
Input 2: 7 8 9 10
11 13 14 1
15 7 12 22
11 21 30 1
Output 2: 11 21 30 1
11 13 14 1
15 7 12 22
7 8 9 10
Approach:
To get the required output, we need to swap the elements of the first and the last row of the stated matrix.
Example
Java
import java.io.*;
public class GFG {
static void swap_First_last( int mat[][])
{
int rws = mat.length;
for ( int j = 0 ; j < mat[ 0 ].length; j++) {
int temp = mat[ 0 ][j];
mat[ 0 ][j] = mat[rws - 1 ][j];
mat[rws - 1 ][j] = temp;
}
}
public static void main(String args[])
throws IOException
{
int mat[][] = { { 2 , 3 , 4 , 5 },
{ 8 , 9 , 6 , 15 },
{ 13 , 22 , 11 , 18 },
{ 19 , 1 , 2 , 0 } };
System.out.println( "Input matrix is as follows : " );
for ( int j = 0 ; j < mat.length; j++) {
for ( int k = 0 ; k < mat[ 0 ].length; k++)
System.out.print(mat[j][k] + " " );
System.out.println();
}
System.out.println(
"Swapped matrix is as follows : " );
swap_First_last(mat);
for ( int j = 0 ; j < mat.length; j++) {
for ( int k = 0 ; k < mat[ 0 ].length; k++)
System.out.print(mat[j][k] + " " );
System.out.println();
}
}
}
|
Output:
Input matrix is as follows :
2 3 4 5
8 9 6 15
13 22 11 18
19 1 2 0
Swapped matrix is as follows :
19 1 2 0
8 9 6 15
13 22 11 18
2 3 4 5
Time Complexity: O(n*m) where n and m are numbers of rows and columns respectively.
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 :
27 Sep, 2022
Like Article
Save Article