python实现螺旋矩阵的填充
2016-06-23 15:12
453 查看
afanty的分析:
关于矩阵(二维数组)填充问题自己动手推推,分析下两个下表的移动规律就很容易咯。
对于螺旋矩阵,不管它是什么鬼,反正就是依次向右、向下、向右、向上移动。
向右移动:横坐标不变,纵坐标加1
向下移动:纵坐标不变,横坐标加1
向右移动:横坐标不变,纵坐标减1
向上移动:纵坐标不变,横坐标减1
代码实现:
#coding=utf-8
import numpy
'''
Author: afanty
Date: 2016/6/23
'''
def helixMatrix(n):
'''实现n维螺旋矩阵的填充
:param n:维数
:return:螺旋矩阵
'''
if not isinstance(n,int) or n <= 0:
raise ValueError('请输入合适的维数')
matrix = numpy.zeros((n,n))
left_top = 0
right_buttom = n-1
number = 1
while left_top < right_buttom:
# 向右移动,横坐标不变,纵坐标+1,number+1
i = left_top
while i < right_buttom:
matrix[left_top][i] = number
i += 1
number += 1
# while
# 向下移动,纵坐标不变,横坐标+1,number+1
i = left_top
while i < right_buttom:
matrix[i][right_buttom] = number
i += 1
number += 1
#while
# 向左移动,横坐标不变,纵坐标-1,number+1
i = right_buttom
while i > left_top:
matrix[right_buttom][i] = number
i -= 1
number += 1
# while
# 向上移动,纵坐标不变,横坐标-1,number+1
i = right_buttom
while i > left_top:
matrix[i][left_top] = number
i -= 1
number += 1
# while
left_top += 1
right_buttom -= 1
# while
if n%2 != 0:
matrix[n/2][n/2] = n*n
return matrix
# end
[[ 1. 2. 3. 4. 5.]
[ 16. 17. 18. 19. 6.]
[ 15. 24. 25. 20. 7.]
[ 14. 23. 22. 21. 8.]
[ 13. 12. 11. 10. 9.]]
关于矩阵(二维数组)填充问题自己动手推推,分析下两个下表的移动规律就很容易咯。
对于螺旋矩阵,不管它是什么鬼,反正就是依次向右、向下、向右、向上移动。
向右移动:横坐标不变,纵坐标加1
向下移动:纵坐标不变,横坐标加1
向右移动:横坐标不变,纵坐标减1
向上移动:纵坐标不变,横坐标减1
代码实现:
#coding=utf-8
import numpy
'''
Author: afanty
Date: 2016/6/23
'''
def helixMatrix(n):
'''实现n维螺旋矩阵的填充
:param n:维数
:return:螺旋矩阵
'''
if not isinstance(n,int) or n <= 0:
raise ValueError('请输入合适的维数')
matrix = numpy.zeros((n,n))
left_top = 0
right_buttom = n-1
number = 1
while left_top < right_buttom:
# 向右移动,横坐标不变,纵坐标+1,number+1
i = left_top
while i < right_buttom:
matrix[left_top][i] = number
i += 1
number += 1
# while
# 向下移动,纵坐标不变,横坐标+1,number+1
i = left_top
while i < right_buttom:
matrix[i][right_buttom] = number
i += 1
number += 1
#while
# 向左移动,横坐标不变,纵坐标-1,number+1
i = right_buttom
while i > left_top:
matrix[right_buttom][i] = number
i -= 1
number += 1
# while
# 向上移动,纵坐标不变,横坐标-1,number+1
i = right_buttom
while i > left_top:
matrix[i][left_top] = number
i -= 1
number += 1
# while
left_top += 1
right_buttom -= 1
# while
if n%2 != 0:
matrix[n/2][n/2] = n*n
return matrix
# end
print helixMatrix(5)输出结果:
[[ 1. 2. 3. 4. 5.]
[ 16. 17. 18. 19. 6.]
[ 15. 24. 25. 20. 7.]
[ 14. 23. 22. 21. 8.]
[ 13. 12. 11. 10. 9.]]
相关文章推荐
- python实现螺旋矩阵的填充
- python实现螺旋矩阵的填充
- python实现螺旋矩阵的填充
- python实现螺旋矩阵的填充
- python cross module global variable
- 尝试用最短的Python代码来实现服务器和代理服务器
- python thread group argument must be none for now
- python之metaclass+singleton(二)
- python day02字典的神奇
- 【Python学习日记】递归和尾递归 以及Python
- python学习第一章(数字,字符串,列表等)
- Python中::(双冒号)的用法
- Python 小练习 阶乘
- 字符串核函数的简单python实现
- python进程、线程、协程
- python随机生成汉字并查看编码方式
- win7 64位 python安装pyquery、lxml
- Python3字符串各种内置函数详解
- 详细记录python的range()函数用法
- 64位Windows下安装xgboost详细参考指南(支持Python2.x和3.x)