I want to rotate a matrix 90 degrees clockwise. This amounts to making the first column in the input the first row of the output, the second column of the input the 2nd row of the output, and the 3rd column of the input the 3rd row of the output. Note that the bottom of the column=the beginning of the row, because of the 90 degree rotation.
For example:
$matrix= [[1, 2, 3]
[4, 5, 6],
[7, 8, 9]];
rotate90degrees($matrix)= [[7, 4, 1],
[8, 5, 2],
[9, 6, 3]]
What I know is I have first transpose the matrix and then swap the columns to rotate the matrix by 90 degrees. How can this be applied to php?
Rotate Matrix 90 Degree Clockwise or Right Rotation The rotation of a matrix involves two steps: First, find the transpose of the given matrix. Swap the elements of the first column with the last column (if the matrix is of 3*3). The second column remains the same.
The formula of this rotation is : RM[x + y - 1][n - x + y] = M[x][y], where RM means rotated matrix, M the initial matrix, and n the dimension of the initial matrix (which is n x n). So, a32, from the third row and second column will get to the fourth row and the fourth column.
I showed you how to transpose an array in answer to a previous question, to rotate 90 degrees, use that transpose logic, and then reverse the order of the values in each row in turn:
$matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
array_unshift($matrix, null);
$matrix = call_user_func_array('array_map', $matrix);
$matrix = array_map('array_reverse', $matrix);
var_dump($matrix);
Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With