Skip to content

Instantly share code, notes, and snippets.

@TheSavior
Created January 17, 2013 23:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TheSavior/4560896 to your computer and use it in GitHub Desktop.
Save TheSavior/4560896 to your computer and use it in GitHub Desktop.
Print array in spiral
<?php
// $a[0] = [ 1, 2, 3, 4]
// $a[1] = [ 5, 6, 7, 8]
// $a[2] = [ 9, 10, 11, 12]
// $a[3] = [13, 14, 15, 16]
// 1 2 3 4 8 12 11 10 9 5 6 7
/*
0,0 3,2
1,1 2,1
2,2 1,0 <- doesn't make sense
additional row:
0,0 3,3
1,1 2,2
2,2 1,1 <- doesn't make sense
*/
// NOTE: ADD SPACES
function printSpiral($array)
{
printSpiralHelper($array, 0, count($array[0])-1, 0, count($array) -1); // array, 0, 0, 0, 1
}
function printSpiralHelper($array, $x1, $x2, $y1, $y2) {
// Single element
if ($x2 == $x1 && $y2 == $y1) {
echo $array[$y1][$x1];
return;
}
// Overlap
else if ($x2 < $x1 || $y2 < $y1)
return;
// top row
$i = $x1;
for (; $i <= $x2; $i++) {
echo $array[$y1][$i];
}
// right col
$j = $y1+1;
for (; $j <= $y2; $j++ ) {
echo $array[$j][$i];
}
// bottom row backwards
$i1 = $i-1;
for (; $i1 >= $x1; $i1--) {
echo $array[$j][$i1];
}
// left col upwards
$k = $y2-1;
for (; $k > $y1; $k--) {
echo $array[$k][$y1];
}
printSpiralHelper($array, $x1+1, $x2-1, $y1+1, $y2-1);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment