Tuesday, September 24, 2024
Google search engine
HomeLanguagesPhp Program to Rotate the matrix right by K times

Php Program to Rotate the matrix right by K times

Given a matrix of size N*M, and a number K. We have to rotate the matrix K times to the right side. 
Examples: 
 

Input :  N = 3, M = 3, K = 2
         12 23 34
         45 56 67
         78 89 91 

Output : 23 34 12
         56 67 45
         89 91 78 


Input :  N = 2, M = 2, K = 2
         1 2
         3 4
         
Output : 1 2
         3 4

 

A simple yet effective approach is to consider each row of the matrix as an array and perform an array rotation. This can be done by copying the elements from K to end of array to starting of array using temporary array. And then the remaining elements from start to K-1 to end of the array.
Lets take an example: 
 

 

PHP




<?php
// PHP program to rotate
// a matrix right by k times
 
// size of matrix
$M = 3;
$N = 3;
 
// function to rotate
// matrix by k times
function rotateMatrix(&$matrix, $k)
{
    global $M, $N;
     
    // temporary array
    // of size M
    $temp = array();
     
    // within the size
    // of matrix
    $k = $k % $M;
     
    for ($i = 0; $i < $N; $i++)
    {
     
        // copy first M-k elements
        // to temporary array
        for ($t = 0;
             $t < $M - $k; $t++)
        $temp[$t] = $matrix[$i][$t];
     
        // copy the elements from
        // k to end to starting
        for ($j = $M - $k;
             $j < $M; $j++)
        $matrix[$i][$j - $M + $k] =
                    $matrix[$i][$j];
     
        // copy elements from
        // temporary array to end
        for ($j = $k; $j < $M; $j++)
        $matrix[$i][$j] = $temp[$j - $k];
    }
}
 
// function to display
// the matrix
function displayMatrix(&$matrix)
{
    global $M, $N;
    for ($i = 0; $i < $N; $i++)
    {
        for ($j = 0; $j < $M; $j++)
        echo ($matrix[$i][$j]." ");
        echo ("
");
    }
}
 
// Driver code
$matrix = array(array(12, 23, 34),
                array(45, 56, 67),
                array(78, 89, 91));
$k = 2;
 
// rotate matrix by k
rotateMatrix($matrix, $k);
 
// display rotated matrix
displayMatrix($matrix);
 
// This code is contributed by
// Manish Shaw(manishshaw1)
?>


Output: 

23 34 12 
56 67 45 
89 91 78

 

Time Complexity: O(N*M) 
Auxiliary Space: O(M)

Please refer complete article on Rotate the matrix right by K times for more details!

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments