剑指offer-顺时针打印矩阵19

题目描述

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下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.
class Solution:
    # matrix类型为二维列表,需要返回列表
    def printMatrix(self, matrix):
        row=len(matrix)
        if row==0:
            return None
        #初始化相关参数
        col=len(matrix[0])
        reslist=[]
        startRow=0
        endRow=row-1
        startCol=0
        endCol=col-1
        while startRow<=endRow and startCol<=endCol:
            #如果就剩下一行
            if startRow==endRow:
                i=startCol
                while i<=endCol:
                    reslist.append(matrix[startRow][i])
                    i+=1
                return reslist
            #如果就剩下一列
            if startCol==endCol:
                i=startCol
                while i<=endRow:
                    reslist.append(matrix[i][startCol])
                    i+=1
                return reslist
            #首行
            i=startCol
            while i<=endCol:
                reslist.append(matrix[startRow][i])
                i+=1
            #末列
            i=startRow+1
            while i<=endRow:
                reslist.append(matrix[i][endCol])
                i+=1
            #末行
            i=endCol-1
            while i>=startCol:
                reslist.append(matrix[endRow][i])
                i-=1
            #首列
            i=endRow-1
            while i>=startRow+1:
                reslist.append(matrix[i][startCol])
                i-=1
            startRow+=1
            startCol+=1
            endRow-=1
            endCol-=1
        return reslist

 

posted @ 2019-02-21 20:14  Cool小子  阅读(98)  评论(0编辑  收藏  举报