code
'''輸入乙個矩陣,按照從外向裡以順時針的順序依次列印出每乙個數字,
例如,如果輸入如下矩陣:
[[ 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
.'''
# -*- coding:utf-8 -*-
class
solution:
# matrix型別為二維列表,需要返回列表
def printmatrix(self, matrix):
if matrix ==none:
return
rows =len(matrix)
columns = len(matrix[0
]) start = 0
while rows > start * 2 and columns > start * 2
: self.printmatrixincircle(matrix, columns, rows, start)
start += 1
print('')
def printmatrixincircle(self, matrix, columns, rows, start):
endx = columns - 1 -start
endy = rows - 1 -start
# 從左到右列印一行
for i in range(start, endx+1
): number =matrix[start][i]
print(
"right
",number, '
', end=''
) # 從上到下列印一行
if start for i in range(start+1, endy+1
): number =matrix[i][endx]
print(
"down
",number, '
', end=''
) # 從右到左列印一行
if start < endx and start for i in range(endx-1, start-1, -1
): number =matrix[endy][i]
print(
"left
",number, '
', end=''
) # 從下到上列印一行
if start < endx and start < endy-1
:
for i in range(endy-1, start, -1
): number =matrix[i][start]
print("up
",number, '
', end=''
)matrix = [[1, 2, 3, 4
], [
5, 6, 7, 8
], [
9, 10, 11, 12
], [
13, 14, 15, 16
]]matrix2 = [[1],[2],[3],[4],[5
]]matrix3 = [[1,2
], [
3,4],
[5,6],
[7,8],
[9,10
]]s =solution()
s.printmatrix(matrix)
s.printmatrix(matrix2)
s.printmatrix(matrix3)
outputs
macname@macdembp ~ %python3 test.pyright
1 right 2 right 3 right 4 down 8 down 12 down 16 left 15 left 14 left 13 up 9 up 5 right 6 right 7 down 11 left 10
right
1 down 2 down 3 down 4 down 5
right
1 right 2 down 4 down 6 down 8 down 10 left 9 up 7 up 5 up 3
macname@macdembp ~ %
順時針列印矩陣
輸入乙個矩陣,按照從外向裡以順時針的順序依次列印出每乙個數字。例如 如果輸入如下矩陣 1 2 3 45 6 7 89 10 11 1213 14 15 16則依次列印出數字 1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10。這個題目 寫的並不好感覺,好多if看著就煩,就是...
順時針列印矩陣
題目 給定乙個矩陣,從外向內順時針列印矩陣中的每乙個數字。例如 給定矩陣 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 輸出應該為 分析 這道題的意思非常直觀,給人的感覺也是so easy,然而實際去做的時候會發現,如果結構劃分的不好,會出現很多的迴圈,而且包括對各種...
順時針列印矩陣
from 題目 輸入乙個矩陣,按照從外向裡以順時針的順序依次列印出每乙個數字。例如 如果輸入如下矩陣 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。網上聽說聽到包括autod...