旋轉打印矩陣

題目測試

給定一個矩陣,順時針旋轉打印矩陣spa

例如輸入code

1  2  3  4blog

5  6  7  8class

9  10  11  12test

13  14  15  16sed

輸出 1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10程序

 

程序di

 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)

 

測試co

 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]))
相關文章
相關標籤/搜索