# # # @param matrix int整型二维数组 # @return int整型一维数组 # class Solution: def spiralOrder(self , matrix ): # write code here if len(matrix)==0: return matrix m = 0 n = len(matrix)-1 #行数 a = 0 b = len(matrix[0])-1 #列数 result = [] #保存结果 #保证输入矩阵行列数量都大于等于2 if n ==0 and b==0: #一行一列 return matrix[0] elif n==0: #一行 return matrix[0] elif b==0: #一列 return [x[0] for x in matrix] while m<n and a < b: result.extend(self.circle(matrix, m, n, a, b)) a+=1 m+=1 n-=1 b-=1 if m==n and a==b:#中间只剩一个值的情况(奇数方阵) result.append(matrix[m][a]) return result elif m>n and a>b:#中间没有值(偶数方阵) pass elif m==n:#中间还剩一行 result.extend(matrix[m][a:b+1]) elif a==b:#中加还有一列 result.extend([x[a] for x in matrix[m:n+1]]) return result def circle(self,matrix,m,n,a,b): ''' 读取m,n行与a,b列交叉形成的矩形边的值 m<n,a<b ''' tem = [] tem.extend(matrix[m][a:b+1]) # 向右 for i in range(m+1,n): #向下 tem.append(matrix[i][b]) tem.extend(reversed(matrix[n][a:b+1])) #向左 for j in range(n-1,m,-1): #向上 tem.append(matrix[j][a]) return tem