# -*- coding:utf-8 -*- ''' 思路很简单,直接模拟这个过程采用四个指针来控制遍历 top=0 ── ── → ┐ right=len(matirx[0]) ┌ ── → ┐ | ↑ ↓ | | ↓ left=0 └ ← ── ┘ bottom=len(matrix) ''' class Solution: # matrix类型为二维列表,需要返回列表 def printMatrix(self, matrix): # write code here if not matrix:#为空时返回[] return [] res=[] self.top=0 self.right=len(matrix[0])-1 self.bottom=len(matrix)-1 self.left=0 while self.left<=self.right and self.top<=self.bottom: for i in range(self.left, self.right+1):#最上面一行 res.append(matrix[self.top][i]) for i in range(self.top+1, self.bottom+1):#最后边一列 res.append(matrix[i][self.right]) if self.top!=self.bottom: for i in range(self.right-1,self.left-1,-1):#最底下一行 res.append(matrix[self.bottom][i]) if self.left!=self.right: for i in range(self.bottom-1,self.top,-1):#最左侧一列 res.append(matrix[i][self.left]) #指针变化 收缩到matrix 里面一圈 self.top+=1 self.right-=1 self.bottom-=1 self.left+=1 return res