题目:54. 螺旋矩阵
链接:https://leetcode-cn.com/problems/spiral-matrix
给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。 示例 1: 输入: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] 输出: [1,2,3,6,9,8,7,4,5] 示例 2: 输入: [ [1, 2, 3, 4], [5, 6, 7, 8], [9,10,11,12] ] 输出: [1,2,3,4,8,12,11,10,9,5,6,7]
解题:
1、直接暴力破解即可,注意边界条件。
代码:
class Solution(object):
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
if len(matrix) == 0:
return []
if len(matrix) == 1:
return matrix[0]
top, bottom = 0, len(matrix) - 1
left, right = 0, len(matrix[0]) - 1
res = []
while top <= bottom and left <= right:
if top <= bottom:
# top:left->right
for j in range(left, right + 1):
res.append(matrix[top][j])
top += 1
if left <= right:
# right: top -> bottom
for i in range(top, bottom + 1):
res.append(matrix[i][right])
right -= 1
if top <= bottom:
# bottom: right -> left
for j in range(right, left - 1, -1):
res.append(matrix[bottom][j])
bottom -= 1
if left <= right:
# left: bottom -> top
for i in range(bottom, top - 1, -1):
res.append(matrix[i][left])
left += 1
return res