版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mabozi08/article/details/88802953
题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 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.
思路:一圈一圈打印
1. 从左到右打印一行
2. 从上到下打印一列,条件是终止行号大于起始行号
3. 从右到左打印一行,条件是圈内至少有两行,即终止行号大于起始行号,且终止列号大于起始列号
4. 从下到上打印一列,至少要三行两列,即终止行号比起始行号至少大2,同时终止列号大于起始列号
# -*- coding:utf-8 -*-
class Solution:
# matrix类型为二维列表,需要返回列表
def printMatrix(self, matrix):
# write code here
rows = len(matrix)
cols = len(matrix[0])
if matrix == None:
return None
start = 0
result = []
while (start*2 < rows and start*2< cols):
end_x = rows-start-1
end_y = cols-start-1
for i in range(start, end_y+1):
result.append(matrix[start][i])
if (start< end_x):
for i in range(start, end_x):
result.append(matrix[i+1][end_y])
if (start < end_x and start < end_y):
for i in range(end_y-1, start-1, -1):
result.append(matrix[end_x][i])
if (start < end_x-1 and start < end_y):
for i in range(end_x-1, start, -1):
result.append(matrix[i][start])
start = start+1
return result