题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
样例:
思路
按照顺时针方向,在矩阵中可以拆分为右->下->左->上四个步骤,因此将分为四个状态进行遍历:
1、右:从左往右,遍历完成后上边界+1;
2、下:从上往下,遍历完成后右边界-1;
3、左:从右往左,遍历完成后下边界+1;
4、上:从下往上,遍历完成后左边界+1;
5、可利用一个计数器完成遍历终止条件,即每打印一个元素,计数器+1,直到计数器等于matrix中的元素个数,退出循环,遍历终止。
代码实现
class Solution(object):
def printMatrix(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
if not matrix:
return []
m = len(matrix)
n = len(matrix[0])
state = 0
p = 0
q = 0
ub = 0
rb = n - 1
db = m - 1
lb = 0
cnt = 0
print_l = []
while cnt < m*n:
if state == 0: # 右
while q <= rb and q >= lb:
print_l.append(matrix[p][q])
cnt += 1 # 计数器
q += 1
q -= 1 # 防止越界
state = 1
ub += 1
p = ub
elif state == 1: # 下
while p >= ub and p <= db:
print_l.append(matrix[p][q])
cnt += 1
p += 1
p -= 1
state = 2
rb -= 1
q = rb
elif state == 2: # 左
while q <= rb and q >= lb:
print_l.append(matrix[p][q])
cnt += 1
q -= 1
q += 1
db -= 1
state = 3
p = db
elif state == 3: # 上
while p >= ub and p <= db:
print_l.append(matrix[p][q])
cnt += 1
p -= 1
p += 1
state = 0
lb += 1
q = lb
return print_l