[python] 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字[顺时针打印矩阵]

算法参考:

剑指offer面试题:输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字 - CSDN博客 http://blog.csdn.net/yanxiaolx/article/details/52254590

剑指offer_输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字 - CSDN博客 http://blog.csdn.net/lingongheng/article/details/52725192

python代码:

方法一:

class Solution:
    # matrix类型为二维列表,需要返回列表
    
    #剑指offer面试题:输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字 - CSDN博客 http://blog.csdn.net/yanxiaolx/article/details/52254590
    def printMatrix(self, matrix):
        # write code here
        if matrix==[[]]:
            return
        row=len(matrix)
        column=len(matrix[0])
        left=0
        right=column-1
        top=0
        boom=row-1
        res=[]
        while right>left and top<boom:
            #从左到右
            for i in range(left,right+1):
                res.append(matrix[top][i])
            #从上到下
            for i in range(top+1,boom+1):
                res.append(matrix[i][right])
            #从右到左
            for i in range(right-1,left-1,-1):
                res.append(matrix[boom][i])
            #从下到上
            for i in range(boom-1,top,-1):
                res.append(matrix[i][left])
            left+=1
            right-=1
            top+=1
            boom-=1
        #剩下一行
        if boom==top and left<right:
            for i in range(left,right+1):
                res.append(matrix[boom][i])
        #剩下一列
        if left==right and boom>top:
            for i in range(top,boom+1):
                res.append(matrix[i][left])
        #剩下一个
        if boom==top and left==right:
            res.append(matrix[left][top])
        return res

方法二:

# -*- coding:utf-8 -*-
class Solution:
    # matrix类型为二维列表,需要返回列表
    def printMatrix(self, matrix):
        # write code here
        if matrix==[[]]:
            return
        row=len(matrix)
        column=len(matrix[0])
        start=0
        res=[]
        while row>start*2 and column>start*2:
            endX=column-1-start
            endY=row-1-start
            #从左到右打印一行
            for i in range(start,endX+1):
                res.append(matrix[start][i])
                #print(matrix[start][i])
            #从上往下打印一列
            if start<endY:
                for i in range(start+1,endY+1):
                    res.append(matrix[i][endX])
                    #print(matrix[i][endX])
            #从右到左打印一行
            if start<endX and start<endY:
                for i in range(endX-1,start-1,-1):
                    res.append(matrix[endY][i])
                    #print(matrix[endY][i])
            #从下到上打印一列
            if start<endX and start<endY-1:
                for i in range(endY-1,start,-1):
                    res.append(matrix[i][start])
                    #print(matrix[i][start])
            start+=1
        return res
        



猜你喜欢

转载自blog.csdn.net/yangnianjinxin/article/details/79243110