classSolution:
defspiralOrder(self, matrix: List[List[int]]) -> List[int]:
m, n = len(matrix), len(matrix[0])
res = []
top, bottom = 0, m - 1
left, right = 0, n - 1while top <= bottom and left <= right:
# 遍历上边界for i inrange(left, right + 1):
res.append(matrix[top][i])
top += 1# 遍历右边界for i inrange(top, bottom + 1):
res.append(matrix[i][right])
right -= 1# 遍历下边界if top <= bottom:
for i inrange(right, left - 1, -1):
res.append(matrix[bottom][i])
bottom -= 1# 遍历左边界if left <= right:
for i inrange(bottom, top - 1, -1):
res.append(matrix[i][left])
left += 1return 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.题目
模拟
classSolution:
defgenerateMatrix(self,n: int) -> List[List[int]]:
matrix = [[0] * n for _ inrange(n)]
num = 1
top, bottom = 0, n - 1
left, right = 0, n - 1while num <= n * n:
# Traverse top rowfor i inrange(left, right + 1):
matrix[top][i] = num
num += 1
top += 1# Traverse right columnfor i inrange(top, bottom + 1):
matrix[i][right] = num
num += 1
right -= 1# Traverse bottom rowfor i inrange(right, left - 1, -1):
matrix[bottom][i] = num
num += 1
bottom -= 1# Traverse left columnfor i inrange(bottom, top - 1, -1):
matrix[i][left] = num
num += 1
left += 1return matrix
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!