這題難度中等,記錄下思路app
第一個會超時,spa
第二個:思想是按斜對角線行進行右下左上交替遍歷,code
1 def traverse(matrix): 2 n=len(matrix)-1 3 m=len(matrix[0])-1 4 result=[] 5 for i in range(m+n+1): 6 if(i % 2 == 0): 7 for j in range(i, -1, -1): 8 x=j 9 y=i-x 10 if x <= n and y <= m: 11 result.append(matrix[x][y]) 12 # elif y > m: 13 # break 14 else: 15 continue 16 else: 17 for j in range(i, -1, -1): 18 y=j 19 x=i-y 20 if x <= n and y <= m: 21 result.append(matrix[x][y]) 22 # elif x > n: 23 # break 24 else: 25 continue 26 return result 27 28 if __name__ == '__main__': 29 ma=[ 30 [ 1, 2, 3 ], 31 [ 4, 5, 6 ], 32 [ 7, 8, 9 ] 33 ] 34 print(traverse(ma))
11blog
1 def diagonial(matrix): 2 m=len(matrix) 3 n=len(matrix[0]) 4 #思想是按斜對角線行進行遍歷 5 #遍歷的方向右下,左上交替進行 6 line=0 7 res=[] 8 tem=[] 9 is_sure=True 10 #對每一行進行循環 斜對角線有m+n-1條 11 while line<(m+n-1): 12 #設置起點 13 if(line<m): 14 x=line 15 y=0 16 else: 17 x=m-1 18 y=line-m-1 19 #每行循環幾回 20 #由於都是從右上開始,因此設置條件x>0,y<n 21 while x>=0 and y <n: 22 # 存儲斜行的元素 23 tem.append(matrix[x][y]) 24 x-=1 25 y+=1 26 #若是是左下開始,則反向添加 27 if(is_sure): 28 tem.reverse() 29 for num in tem: 30 res.append(num) 31 line+=1 32 return res 33 34 35 if __name__ == '__main__': 36 matrix=[ 37 [ 1, 2, 3 ], 38 [ 4, 5, 6 ], 39 [ 7, 8, 9 ] 40 ] 41 print(diagonial(matrix))