螺旋矩阵是一个在二维空间中,元素按螺旋顺序排列的矩阵。以下是一个使用PHP创建和遍历螺旋矩阵的实例。
1. 创建螺旋矩阵
我们需要定义一个函数来创建一个给定的行数和列数的螺旋矩阵。
```php
function createSpiralMatrix($rows, $cols) {
$matrix = array_fill(0, $rows, array_fill(0, $cols, 0));
$value = 1;
$startRow = 0;
$endRow = $rows - 1;
$startCol = 0;
$endCol = $cols - 1;
while ($startRow <= $endRow && $startCol <= $endCol) {
// Top row
for ($i = $startCol; $i <= $endCol; $i++) {
$matrix[$startRow][$i] = $value++;
}
$startRow++;
// Right column
for ($i = $startRow; $i <= $endRow; $i++) {
$matrix[$i][$endCol] = $value++;
}
$endCol--;
// Bottom row
if ($startRow <= $endRow) {
for ($i = $endCol; $i >= $startCol; $i--) {
$matrix[$endRow][$i] = $value++;
}
$endRow--;
}
// Left column
if ($startCol <= $endCol) {
for ($i = $endRow; $i >= $startRow; $i--) {
$matrix[$i][$startCol] = $value++;
}
$startCol++;
}
}
return $matrix;
}
```
2. 遍历螺旋矩阵
接下来,我们需要一个函数来遍历这个螺旋矩阵。
```php
function printSpiralMatrix($matrix) {
$rows = count($matrix);
$cols = count($matrix[0]);
$startRow = 0;
$endRow = $rows - 1;
$startCol = 0;
$endCol = $cols - 1;
while ($startRow <= $endRow && $startCol <= $endCol) {
// Top row
for ($i = $startCol; $i <= $endCol; $i++) {
echo $matrix[$startRow][$i] . "

