当前位置: 面试刷题>> 矩阵(经典算法150题)
### 题目描述
**题目:矩阵的螺旋遍历**
给定一个`m x n`的矩阵(`m`行,`n`列),请按照螺旋顺序返回矩阵中的所有元素。螺旋顺序指的是从左上角开始,首先向右遍历,然后向下,接着向左,最后向上,以此类推,直到遍历完所有元素。
**示例**:
输入矩阵:
```
[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
```
输出:`[1, 2, 3, 6, 9, 8, 7, 4, 5]`
### PHP 示例代码
```php
function spiralOrder($matrix) {
if (empty($matrix)) return [];
$result = [];
$top = 0;
$bottom = count($matrix) - 1;
$left = 0;
$right = count($matrix[0]) - 1;
while ($left <= $right && $top <= $bottom) {
// Traverse right
for ($i = $left; $i <= $right; $i++) {
$result[] = $matrix[$top][$i];
}
$top++;
// Traverse down
for ($i = $top; $i <= $bottom; $i++) {
$result[] = $matrix[$i][$right];
}
$right--;
if ($top <= $bottom) {
// Traverse left
for ($i = $right; $i >= $left; $i--) {
$result[] = $matrix[$bottom][$i];
}
$bottom--;
}
if ($left <= $right) {
// Traverse up
for ($i = $bottom; $i >= $top; $i--) {
$result[] = $matrix[$i][$left];
}
$left++;
}
}
return $result;
}
// 示例用法
$matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
print_r(spiralOrder($matrix));
```
### Python 示例代码
```python
def spiralOrder(matrix):
if not matrix:
return []
result = []
top, bottom = 0, len(matrix) - 1
left, right = 0, len(matrix[0]) - 1
while left <= right and top <= bottom:
# Traverse right
for i in range(left, right + 1):
result.append(matrix[top][i])
top += 1
# Traverse down
for i in range(top, bottom + 1):
result.append(matrix[i][right])
right -= 1
if top <= bottom:
# Traverse left
for i in range(right, left - 1, -1):
result.append(matrix[bottom][i])
bottom -= 1
if left <= right:
# Traverse up
for i in range(bottom, top - 1, -1):
result.append(matrix[i][left])
left += 1
return result
# 示例用法
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(spiralOrder(matrix))
```
### JavaScript 示例代码
```javascript
function spiralOrder(matrix) {
if (!matrix.length) return [];
let result = [];
let top = 0, bottom = matrix.length - 1;
let left = 0, right = matrix[0].length - 1;
while (left <= right && top <= bottom) {
// Traverse right
for (let i = left; i <= right; i++) {
result.push(matrix[top][i]);
}
top++;
// Traverse down
for (let i = top; i <= bottom; i++) {
result.push(matrix[i][right]);
}
right--;
if (top <= bottom) {
// Traverse left
for (let i = right; i >= left; i--) {
result.push(matrix[bottom][i]);
}
bottom--;
}
if (left <= right) {
// Traverse up
for (let i = bottom; i >= top; i--) {
result.push(matrix[i][left]);
}
left++;
}
}
return result;
}
// 示例用法
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
console.log(spiralOrder(matrix));
```
这些示例代码均实现了矩阵的螺旋遍历,并给出了具体的示例用法。在面试中,你可以根据面试官的要求选择使用哪种编程语言进行解答。