旋转打印矩阵
题目
给定一个矩阵,顺时针旋转打印矩阵
例如输入
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
程序
1 def exe(data, cxindex, cyindex, mxindex, myindex): 2 """ 3 旋转打印矩阵 4 :param data: 矩阵 5 :param cxindex: 要打印的左上角位置的x下标 6 :param cyindex: 要打印的左上角位置的y下标 7 :param mxindex: 本次要打印的矩阵的行数 8 :param myindex: 本次要打印的矩阵的列数 9 """ 10 if cxindex == mxindex - 1 and cyindex == myindex - 1: # 一个单独的数字 11 print(data[cxindex][cyindex]) 12 elif cxindex == mxindex - 1 and not cyindex == myindex - 1: # 单独的一行数字 13 for i in range(cyindex, myindex): 14 print(data[cxindex][i]) 15 elif not cxindex == mxindex - 1 and cyindex == myindex - 1: # 单独的一列数字 16 for i in range(cxindex, mxindex): 17 print(data[i][cyindex]) 18 else: 19 for i in range(cyindex, myindex - 1): 20 print(data[cxindex][i]) 21 for i in range(cxindex, mxindex - 1): 22 print(data[i][myindex - 1]) 23 for i in reversed(range(cyindex + 1, myindex)): 24 print(data[mxindex - 1][i]) 25 for i in reversed(range(cxindex + 1, mxindex)): 26 print(data[i][cyindex]) 27 if cxindex + 1 <= mxindex - 2 and cyindex + 1 <= myindex - 2: # 有任意一个大于的话,则会越界 28 exe(data, cxindex + 1, cyindex + 1, mxindex - 1, myindex - 1)
测试
1 def test(): 2 data = [ 3 [1, 2, 3, 4], 4 [5, 6, 7, 8], 5 [9, 10, 11, 12], 6 [13, 14, 15, 16], 7 [17, 18, 19, 20], 8 [1, 2, 3, 4], 9 [5, 6, 7, 8], 10 [9, 10, 11, 12], 11 [13, 14, 15, 16], 12 [17, 18, 19, 20] 13 ] 14 exe(data, 0, 0, len(data), len(data[0]))