下面的代码使用了额外的空间。
<?php
function rotate90degrees()
{
$matrix = [[1,2,3],
[4,5,6],
[7,8,9]];
$k = 0;
$len = count($matrix[0]);
$tmp = [];
// Create a new matrix with [[0,0,0],[0,0,0],[0,0,0]]
while($k < $len) {
$row = [];
$l = 0;
while($l < $len) {
$row[] = 0;
$l++;
}
$tmp[] = $row;
$k++;
}
// Rotate through the given matrix and fill out the above created new matrix
for($i=0; $i<$len; $i++) {
for($j=$len-1; $j>=0; $j--) {
$tmp[$i][$j] = $matrix[$j][$i];
}
$tmp[$i] = array_reverse($tmp[$i]);
}
return $matrix;
}
以下函数不占用额外空间。
<?php
function rotate90degreesWithoutAdditionalSpace()
{
$matrix = [[1,2,3],
[4,5,6],
[7,8,9]];
$len = count($matrix);
// Swap the rows columns.
for($i=0; $i<$len; $i++) {
for($j=$i; $j<$len; $j++) {
$tmp = $matrix[$i][$j];
$matrix[$i][$j] = $matrix[$j][$i];
$matrix[$j][$i] = $tmp;
}
}
// Swap the elements from both ends of each row until the centered element in the row.
for($i=0; $i<$len; $i++) {
for($j=0; $j<floor($len/2); $j++) {
$tmp = $matrix[$i][$j];
$matrix[$i][$j] = $matrix[$i][$len-1-$j];
$matrix[$i][$len-1-$j] = $tmp;
}
}
return $matrix;
}