剑指offer之019-顺时针打印矩阵

题目描述

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.

思路

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

用一个bool数组标记走过的路,到底了就按照 右→下→左→上→右 的方式修改运动方向。

def printMatrix(matrix):
    # write code here
    walked = [[False] * (len(matrix[0])+1) for _ in range(len(matrix)+1)]
    for j in range(len(walked[-1])):
        walked[-1][j] = True
    for i in range(len(walked)):
        walked[i][-1] = True
    len_row = len(matrix) - 1
    len_col = len(matrix[0]) - 1
    res = []
    i = 0
    j = 0
    direction = 0  # 0向右,1向下,2向左,3向上

    while not walked[i][j]:
        res.append(matrix[i][j])
        walked[i][j] = True
        if direction == 0: # right
            if j < len_col and not walked[i][j+1]:
                j += 1
            else:
                direction = 1
                i += 1
        elif direction == 1: # down
            if i < len_row and not walked[i+1][j]:
                i += 1
            else:
                direction = 2
                j -= 1
        elif direction == 2:  # left
            if j > 0 and not walked[i][j-1]:
                j -= 1
            else:
                direction = 3
                i -= 1
        elif direction == 3:  # up
            if i > 0 and not walked[i-1][j]:
                i -= 1

关于明柳梦少

坚守自己的原则,不随波逐流。