顺时针打印矩阵(方向控制)
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]])
相关文章推荐
- 顺时针方向打印矩阵
- 顺时针方向打印矩阵
- 1391:顺时针打印矩阵 @jobdu
- 顺时针打印矩阵
- 20_顺时针打印矩阵
- 【剑指offer】4.2画图让抽象问题形象化——面试题20:顺时针打印矩阵
- 数据结构之顺时针打印矩阵
- 20顺时针打印矩阵python
- 【剑指offer】顺时针打印矩阵
- 顺时针打印矩阵
- 【剑指**】29.顺时针打印矩阵
- 剑指offer-4-面试题20:顺时针打印矩阵(画图使抽象问题形象化)
- 顺时针打印矩阵
- 剑指offer系列-T20顺时针打印矩阵
- 顺时针打印矩阵
- 顺时针打印矩阵
- java实现打印功能并控制打印方向
- 顺时针打印矩阵
- 剑指offer之面试题20顺时针打印矩阵
- 剑指offer 面试题20:顺时针打印矩阵及其变形(LeetCode54. Spiral Matrix旋转矩阵) 题解