题目:
顺时针打印矩阵
描述:
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,
例如,
如果输入如下矩阵:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
则依次打印出数字:1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
<?phpfunction printMatrix($matrix)
{$row = count($matrix);$col = count($matrix[0]);$len = $row * $col;$top = 0; $x = 0; $y = 0;$list = array();while($top+1 < $len){while($y+1 < $col && $matrix[$x][$y+1] !== null){array_push($list, $matrix[$x][$y]);$matrix[$x][$y] = null;$y++;$top++;}while($x+1 < $row && $matrix[$x+1][$y] !== null){array_push($list, $matrix[$x][$y]);$matrix[$x][$y] = null;$x++;$top++;}while($y-1 >= 0 && $matrix[$x][$y-1] !== null){array_push($list, $matrix[$x][$y]);$matrix[$x][$y] = null;$y--;$top++;}while($x-1 >= 0 && $matrix[$x-1][$y] != null){array_push($list, $matrix[$x][$y]);$matrix[$x][$y] = null;$x--;$top++;}}array_push($list, $matrix[$x][$y]);return $list;
}