输入包含多行,第一行两个整数n和m,代表矩阵的行数和列数,接下来n行,每行m个整数,代表矩阵matrix。
输出包含一行,n*m个整数,代表顺时针转圈输出的矩阵matrix。
4 4 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
额外空间复杂度O(1)
def spiralOrderPrint(matrix, res): tR = 0 # 左上角的行 tC = 0 # 左上角的列 dR = len(matrix) - 1 # 右下角的行 dC = len(matrix[0]) -1 # 右下角的列 while tR <= dR and tC <= dC: printEdge(matrix, tR, tC, dR, dC, res) tR += 1 tC += 1 dR -= 1 dC -= 1 return res def printEdge(matrix, tR, tC, dR, dC, res): if tR == dR: # 当矩阵只有一行的时候 for i in range(tC, dC+1): res.append(matrix[tR][i]) # 当矩阵只有一列的时候 elif tC == dC: for i in range(tR, dR+1): res.append(matrix[i][tC]) else: curC = tC curR = tR while curC != dC: res.append(matrix[tR][curC]) curC += 1 while curR != dR: res.append(matrix[curR][dC]) curR += 1 while curC != tC: res.append(matrix[dR][curC]) curC -= 1 while curR != tR: res.append(matrix[curR][tC]) curR -= 1 if __name__ == '__main__': import sys n, m = list(map(int, sys.stdin.readline().split())) i = 0 matrix = [] while i < n: matrix.append(list(map(int, sys.stdin.readline().split()))) i+=1 res = [] res1 = spiralOrderPrint(matrix, res) res2 = '' for i in res1: res2 += str(i)+' ' print(res2)