Skip to content

Instantly share code, notes, and snippets.

@cjzeven
Created September 26, 2019 10:46
Show Gist options
  • Save cjzeven/7e8b3c3767a74054eec9f10730500eeb to your computer and use it in GitHub Desktop.
Save cjzeven/7e8b3c3767a74054eec9f10730500eeb to your computer and use it in GitHub Desktop.
Spiral matrix
<?php
function matrix($n)
{
$result = [];
for ($i = 0; $i < $n; $i++) {
array_push($result, range(0, $n - 1));
}
$start_row = 0;
$end_row = $n - 1;
$start_column = 0;
$end_column = $n - 1;
$counter = 1;
while ($start_row <= $end_row && $start_column <= $end_column) {
for ($i = $start_column; $i <= $end_column; $i++) {
$result[$start_row][$i] = $counter;
$counter++;
}
$start_row++;
for ($i = $start_row; $i <= $end_row; $i++) {
$result[$i][$end_column] = $counter;
$counter++;
}
$end_column--;
for ($i = $end_column; $i >= $start_column; $i--) {
$result[$end_row][$i] = $counter;
$counter++;
}
$end_row--;
for ($i = $end_row; $i >= $start_row; $i--) {
$result[$i][$start_column] = $counter;
$counter++;
}
$start_column++;
}
return $result;
}
// [[1, 2, 3, 4],
// [12, 13, 14, 5],
// [11, 16, 15, 6],
// [10, 9, 8, 7]];
foreach (matrix(3) as $row) {
echo join(', ', $row);
echo "<br>";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment