您的位置:首页 > 编程语言 > Python开发

顺时针打印矩阵(方向控制)

2017-01-25 01:06 239 查看


题目描述

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 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.

类似于nyoj上面33题的蛇形填空

# -*- coding:utf-8 -*-
class Solution:
# matrix类型为二维列表,需要返回列表
def printMatrix(self, matrix):
# write code here
# 获取行
row = len(matrix)
# 获取列
col = len(matrix[0])
x = num = y = 0
li = []
li.append(matrix[0][0])
matrix[0][0] = None
num += 1
while num < row * col:
# 先判断y轴方向上面的
while y + 1 < col and matrix[x][y + 1] != None:
num += 1
li.append(matrix[x][y + 1])
matrix[x][y + 1] = None
y += 1
# 再判断x轴方向
while x + 1 < row and matrix[x + 1][y] != None:
num += 1
li.append(matrix[x + 1][y])
matrix[x + 1][y] = None
x += 1
# y轴负方向
while y - 1 >= 0 and matrix[x][y - 1] != None:
num += 1
li.append(matrix[x][y - 1])
matrix[x][y - 1] = None
y -= 1
# x轴负方向
while x - 1 >= 0 and matrix[x - 1][y] != None:
num += 1
li.append(matrix[x - 1][y])
matrix[x - 1][y] = None
x -= 1

return li

if __name__ == "__main__":
a = Solution()
print a.printMatrix([[ 0, 1, 2, 3],[ 4, 5, 6, 7],[ 8, 9, 10, 11],[12, 13, 14, 15]])
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ACM python