Skip to content

Instantly share code, notes, and snippets.

@anujsinghwd
Created November 17, 2018 10:53
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 anujsinghwd/ccd240d78499b04fc1cdf2c578281f52 to your computer and use it in GitHub Desktop.
Save anujsinghwd/ccd240d78499b04fc1cdf2c578281f52 to your computer and use it in GitHub Desktop.
Given a 2D matrix of size M*N. Traverse and print the matrix in spiral form.
<?php
$arr = array(array(1,2,3,4),array(5,6,7,8),array(9,10,11,12),array(13,14,15,16));
$k = 0;
$m = 3;//last row
$l = 0;
$n = 3; //last column
while($k <= $m && $l <= $n){
for($i=0;$i<=$m;$i++){
echo $arr[$k][$i];
}
$k++;
for($i=$k;$i<=$n;$i++){
echo $arr[$i][$n];
}
$n--;
if($k <= $m){
for($i=$n;$i>=$l;$i--){
echo $arr[$m][$i];
}
$m--;
}
if($l <= $n){
for($i=$m;$i>=$k;$i--){
echo $arr[$i][$l];
}
$l++;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment