标签:row 返回 逆时针 print cond utf-8 for else title
暴力写:
# -*- coding:utf-8 -*- class Solution: # matrix类型为二维列表,需要返回列表 def __init__(self): self.result=[] def printMatrix(self, matrix): # write code here row=len(matrix) col=len(matrix[0]) if row==col==0: return self.reuslt elif row==1: self.result+=matrix[0] return self.result elif col==1: for i in range(row): self.result+=matrix[i] return self.result elif row==2: self.result+=matrix[0] self.result+=matrix[1][::-1] return self.result elif col==2: self.result+=matrix[0] for i in range(1,row): self.result.append(matrix[i][1]) for j in range(1,row)[::-1]: self.result.append(matrix[j][0]) return self.result else: #first loop self.result+=matrix[0] #second loop for i in range(1,row): self.result.append(matrix[i][col-1]) #third loop self.result+=matrix[row-1][:-1][::-1] #fourth loop for j in range(1,row-1)[::-1]: self.result.append(matrix[j][0]) new_matrix=[list[1:col-1] for list in matrix[1:row-1]] self.printMatrix(new_matrix) return self.result
先遍历第一行:在逆时针翻转
# -*- coding:utf-8 -*- class Solution: # matrix类型为二维列表,需要返回列表 def turn(self,matrix): turn_matrix=[] row,col=len(matrix),len(matrix[0]) for j in range(col)[::-1]: tmp=[] for i in range(row): tmp.append(matrix[i][j]) turn_matrix.append(tmp) return turn_matrix def printMatrix(self, matrix): # write code here res=[] while(matrix): if len(matrix)==1: res.extend(matrix[0]) return res elif len(matrix)==2: res.extend(matrix[0]) res.extend(matrix[1][::-1]) return res else: res.extend(matrix[0]) matrix=self.turn(matrix[1:]) return res
标签:row 返回 逆时针 print cond utf-8 for else title
原文地址:https://www.cnblogs.com/hit-joseph/p/11907846.html