Php Program to Interchange elements of first and last rows in matrix
Given a 4 x 4 matrix, we have to interchange the elements of first and last row and show the resulting matrix.
Examples :
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
Input : 9 7 5 1
2 3 4 1
5 6 6 5
1 2 3 1
Output : 1 2 3 1
2 3 4 1
5 6 6 5
9 7 5 1
The approach is very simple, we can simply swap the elements of first and last row of the matrix inorder to get the desired matrix as output.
Below is the implementation of the approach :
PHP
<?php
$n = 4;
function interchangeFirstLast(& $m )
{
global $n ;
$rows = $n ;
for ( $i = 0; $i < $n ; $i ++)
{
$t = $m [0][ $i ];
$m [0][ $i ] = $m [ $rows - 1][ $i ];
$m [ $rows - 1][ $i ] = $t ;
}
}
$m = array ( array (8, 9, 7, 6),
array (4, 7, 6, 5),
array ( 3, 2, 1, 8),
array (9, 9, 7, 7));
interchangeFirstLast( $m );
for ( $i = 0; $i < $n ; $i ++)
{
for ( $j = 0; $j < $n ; $j ++)
echo $m [ $i ][ $j ] . " " ;
echo "
";
}
?>
|
Output :
9 9 7 7
4 7 6 5
3 2 1 8
8 9 7 6
Time Complexity: O(N) where N is no of rows; as we are using single loop for interchanging first and last rows of a given matrix.
Auxiliary Space: O(1), as we are not using any extra space.
Please refer complete article on Interchange elements of first and last rows in matrix for more details!
Last Updated :
24 Jul, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...