题目描述

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下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,端点标识减1即可完成顺时针遍历矩阵。
完整代码

# -*- coding:utf-8 -*-
class Solution:
    # matrix类型为二维列表,需要返回列表
    def printMatrix(self, matrix):
        # write code here
        i = 0
        length = len(matrix[0])
        j = 0
        height = len(matrix)
        result = []
        label = []
        for m in range(length):
            label.append('a')
        entry = True
        while entry:
            i_t = i
            j_t = j
            e = False
            while i_t >= i and i_t < length and j_t >= j and j_t < height:
                print(1, j_t, i_t)
                if matrix[j_t][i_t] != 'a':
                    result.append(matrix[j_t][i_t])
                    matrix[j_t][i_t] = 'a'
                i_t += 1
                e = True
            if e:
                i_t -= 1
                e = False
            while i_t >= i and i_t < length and j_t >= j and j_t < height:
                print(2, j_t, i_t)
                if matrix[j_t][i_t] != 'a':
                    result.append(matrix[j_t][i_t])
                    matrix[j_t][i_t] = 'a'
                j_t += 1
                e = True
            if e:
                j_t -= 1
                e = False
            while i_t >= i and i_t < length and j_t >= j and j_t < height:
                print(3, j_t, i_t)
                if matrix[j_t][i_t] != 'a':
                    result.append(matrix[j_t][i_t])
                    matrix[j_t][i_t] = 'a'
                i_t -= 1
                e = True
            if e:
                i_t += 1
                e = False
            while i_t >= i and i_t < length and j_t >= j and j_t < height:
                print(4, j_t, i_t)
                if matrix[j_t][i_t] != 'a':
                    result.append(matrix[j_t][i_t])
                    matrix[j_t][i_t] = 'a'
                j_t -= 1
            if matrix.count(label) == len(matrix):
                entry = False
            i += 1
            j += 1
            length -= 1
            height -= 1
        return result