Created
November 17, 2018 10:53
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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