54.题目
![]()
python
模拟
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
m, n = len(matrix), len(matrix[0])
res = []
top, bottom = 0, m - 1
left, right = 0, n - 1
while top <= bottom and left <= right:
# 遍历上边界
for i in range(left, right + 1):
res.append(matrix[top][i])
top += 1
# 遍历右边界
for i in range(top, bottom + 1):
res.append(matrix[i][right])
right -= 1
# 遍历下边界
if top <= bottom:
for i in range(right, left - 1, -1):
res.append(matrix[bottom][i])
bottom -= 1
# 遍历左边界
if left <= right:
for i in range(bottom, top - 1, -1):
res.append(matrix[i][left])
left += 1
return res
JavaScript
按层模拟
var spiralOrder = function(matrix) {
if (!matrix.length || !matrix[0].length) {
return [];
}
const rows = matrix.length, columns = matrix[0].length;
const order = []; //结果数组
let left = 0, right = columns - 1, top = 0, bottom = rows - 1;
while (left <= right && top <= bottom) {
for (let column = left; column <= right; column++) {//左到右
order.push(matrix[top][column]);
}
for (let row = top + 1; row <= bottom; row++) {//上到下
order.push(matrix[row][right]);
}
if (left < right && top < bottom) {
for (let column = right - 1; column > left; column--) {//右到左
order.push(matrix[bottom][column]);
}
for (let row = bottom; row > top; row--) {//下到上
order.push(matrix[row][left]);
}
}
//外面一圈遍历完后,向内收缩指针
[left, right, top, bottom] = [left + 1, right - 1, top + 1, bottom - 1];
}
return order;
};
59.题目
![]()
模拟
class Solution:
def generateMatrix(self,n: int) -> List[List[int]]:
matrix = [[0] * n for _ in range(n)]
num = 1
top, bottom = 0, n - 1
left, right = 0, n - 1
while num <= n * n:
# Traverse top row
for i in range(left, right + 1):
matrix[top][i] = num
num += 1
top += 1
# Traverse right column
for i in range(top, bottom + 1):
matrix[i][right] = num
num += 1
right -= 1
# Traverse bottom row
for i in range(right, left - 1, -1):
matrix[bottom][i] = num
num += 1
bottom -= 1
# Traverse left column
for i in range(bottom, top - 1, -1):
matrix[i][left] = num
num += 1
left += 1
return matrix