剑指 Offer 29. 顺时针打印矩阵
描述
略
思路
画好图,定义好(x1, y1, x2, y2)的物理意义
- 注意循环条件
- 注意终止位置
- 更新内外层
图片来自https://leetcode-cn.com/problems/shun-shi-zhen-da-yin-ju-zhen-lcof/solution/shun-shi-zhen-da-yin-ju-zhen-by-leetcode-solution/
class Solution(object):
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
if not matrix:
return []
ret = []
x1, y1, x2, y2 = 0, 0, len(matrix) - 1, len(matrix[0]) - 1
while x1 <= x2 and y1 <= y2:
for i in range(y1, y2 + 1):
ret.append(matrix[x1][i])
for i in range(x1 + 1, x2 + 1):
ret.append(matrix[i][y2])
if x1 < x2 and y1 < y2:
for i in range(y2 - 1, y1, -1):
ret.append(matrix[x2][i])
for i in range(x2, x1, -1):
ret.append(matrix[i][y1])
x1, y1, x2, y2 = x1 + 1, y1 + 1, x2 - 1, y2 - 1
return ret