Spiral Matrix

Traverse a 2D matrix in spiral order starting from the top-left corner.

Code

Algorithms
$result = [];
$top = 0; $bottom = count($matrix) - 1; $left = 0; $right = count($matrix[0]) - 1;
while ($top <= $bottom && $left <= $right) {
    for ($i = $left; $i <= $right; $i++) $result[] = $matrix[$top][$i];
    $top++;
    for ($i = $top; $i <= $bottom; $i++) $result[] = $matrix[$i][$right];
    $right--;
    if ($top <= $bottom) {
        for ($i = $right; $i >= $left; $i--) $result[] = $matrix[$bottom][$i];
        $bottom--;
    }
    if ($left <= $right) {
        for ($i = $bottom; $i >= $top; $i--) $result[] = $matrix[$i][$left];
        $left++;
    }
}
return $result;

Parameters

2D matrix

Server

More PHP Snippets