function PrintMatrixInSpiralForm($matrix) {
if ($matrix == NULL || count($matrix) == 0) {
return;
}
$top = 0;
$bottom = count($matrix) - 1;
$left = 0;
$right = count($matrix[0]) - 1;
while (true) {
if ($left > $right) {
break;
}
// top row
for ($i = $left; $i <= $right; $i++) {
echo $matrix[$top][$i] . " ";
}
echo "\n";
$top++; // next row
// next row
if ($top > $bottom) {
break;
}
// right column
for ($i = $top; $i <= $bottom; $i++) {
echo $matrix[$i][$right] . " ";
}
echo "\n";
$right--; // previous column
// previous column
if ($left > $right) {
break;
}
// bottom row
for ($i = $right; $i >= $left; $i--) {
echo $matrix[$bottom][$i] . " ";
}
echo "\n";
$bottom--; // previous row
// previous row
if ($top > $bottom) {
break;
}
// left column
for ($i = $bottom; $i >= $top; $i--) {
echo $matrix[$i][$left] . " ";
}
echo "\n";
$left++; // next column
}
}
$matrix = array(
array(1, 2, 3, 4),
array(5, 6, 7, 8),
array(9, 10, 11, 12),
array(13, 14, 15, 16)
);
PrintMatrixInSpiralForm($matrix);
/*
run:
1 2 3 4
8 12 16
15 14 13
9 5
6 7
11
10
*/