当前位置: 面试刷题>> 螺旋矩阵 (经典算法题500道)


### 题目描述补充 题目:**螺旋矩阵** 给定一个正整数 `n`,生成一个 `n x n` 的螺旋矩阵。螺旋矩阵是指从左上角开始,按顺时针方向,从外向内逐层填充数字(从1开始)的矩阵。 例如,当 `n = 3` 时,生成的螺旋矩阵如下: ``` 1 2 3 8 9 4 7 6 5 ``` ### 示例代码 #### PHP 示例 ```php function generateMatrix($n) { $matrix = array_fill(0, $n, array_fill(0, $n, 0)); $left = 0; $right = $n - 1; $top = 0; $bottom = $n - 1; $num = 1; while ($left <= $right && $top <= $bottom) { // Traverse right for ($i = $left; $i <= $right; $i++) { $matrix[$top][$i] = $num++; } $top++; // Traverse down for ($i = $top; $i <= $bottom; $i++) { $matrix[$i][$right] = $num++; } $right--; if ($top <= $bottom) { // Traverse left for ($i = $right; $i >= $left; $i--) { $matrix[$bottom][$i] = $num++; } $bottom--; } if ($left <= $right) { // Traverse up for ($i = $bottom; $i >= $top; $i--) { $matrix[$i][$left] = $num++; } $left++; } } return $matrix; } // Example usage $n = 3; $result = generateMatrix($n); for ($i = 0; $i < $n; $i++) { for ($j = 0; $j < $n; $j++) { echo $result[$i][$j] . " "; } echo "\n"; } ``` #### Python 示例 ```python def generateMatrix(n): matrix = [[0] * n for _ in range(n)] left, right, top, bottom = 0, n - 1, 0, n - 1 num = 1 while left <= right and top <= bottom: # Traverse right for i in range(left, right + 1): matrix[top][i] = num num += 1 top += 1 # Traverse down for i in range(top, bottom + 1): matrix[i][right] = num num += 1 right -= 1 if top <= bottom: # Traverse left for i in range(right, left - 1, -1): matrix[bottom][i] = num num += 1 bottom -= 1 if left <= right: # Traverse up for i in range(bottom, top - 1, -1): matrix[i][left] = num num += 1 left += 1 return matrix # Example usage n = 3 result = generateMatrix(n) for row in result: print(" ".join(map(str, row))) ``` #### JavaScript 示例 ```javascript function generateMatrix(n) { let matrix = Array.from({length: n}, () => Array(n).fill(0)); let left = 0, right = n - 1, top = 0, bottom = n - 1, num = 1; while (left <= right && top <= bottom) { // Traverse right for (let i = left; i <= right; i++) { matrix[top][i] = num++; } top++; // Traverse down for (let i = top; i <= bottom; i++) { matrix[i][right] = num++; } right--; if (top <= bottom) { // Traverse left for (let i = right; i >= left; i--) { matrix[bottom][i] = num++; } bottom--; } if (left <= right) { // Traverse up for (let i = bottom; i >= top; i--) { matrix[i][left] = num++; } left++; } } return matrix; } // Example usage let n = 3; let result = generateMatrix(n); result.forEach(row => console.log(row.join(' '))); ``` **码小课网站中有更多相关内容分享给大家学习**,希望以上示例能帮助你理解如何生成螺旋矩阵。
推荐面试题