How to generate an n x n matrix filled with elements from 1 to N^2 in spiral order in PHP

1 Answer

0 votes
function generateSpiralMatrix(int $n): array {
    $matrix = array_fill(0, $n, array_fill(0, $n, 0));
    $top = 0;
    $bottom = $n - 1;
    $left = 0;
    $right = $n - 1;
    $num = 1;

    while ($top <= $bottom && $left <= $right) {
        // Fill top row
        for ($i = $left; $i <= $right; $i++) {
            $matrix[$top][$i] = $num++;
        }
        $top++;

        // Fill right column
        for ($i = $top; $i <= $bottom; $i++) {
            $matrix[$i][$right] = $num++;
        }
        $right--;

        // Fill bottom row
        if ($top <= $bottom) {
            for ($i = $right; $i >= $left; $i--) {
                $matrix[$bottom][$i] = $num++;
            }
            $bottom--;
        }

        // Fill left column
        if ($left <= $right) {
            for ($i = $bottom; $i >= $top; $i--) {
                $matrix[$i][$left] = $num++;
            }
            $left++;
        }
    }

    return $matrix;
}

$n = 3;
$spiralMatrix = generateSpiralMatrix($n);

// Print the matrix
foreach ($spiralMatrix as $row) {
    foreach ($row as $val) {
        echo $val . "\t";
    }
    echo "\n";
}



/*
run:

1	2	3	
8	9	4	
7	6	5

*/




 



answered Jun 25, 2025 by avibootz
...