left = 0 right = columns - 1 top = 0 bottom = rows - 1 result = [] while total > 0: for i inrange(left, right+1): # 通过总数控制循环是否停止 if total == 0: break # print(top, i) result.append(matrix[top][i]) total = total - 1 # 每次循环完成后,某一个坐标需要改变 top += 1
for i inrange(top, bottom+1): if total == 0: break # print(i, right) result.append(matrix[i][right]) total = total - 1 right = right - 1
for i inrange(right, left-1, -1): if total == 0: break # print(bottom, i) result.append(matrix[bottom][i]) total = total - 1 bottom = bottom - 1
for i inrange(bottom, top-1, -1): if total == 0: break # print("----", i, left) result.append(matrix[i][left]) total = total - 1 left += 1 return result