Python实现螺旋矩阵的填充算法示例

作者:afanty_mo 时间:2022-06-30 00:18:47 

本文实例讲述了Python实现螺旋矩阵的填充算法。分享给大家供大家参考,具体如下:

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
print("脚本之家测试结果:")
print helixMatrix(5)

运行结果:

Python实现螺旋矩阵的填充算法示例

希望本文所述对大家Python程序设计有所帮助。

来源:http://blog.csdn.net/mo_yihua/article/details/51743722

标签:Python,矩阵,算法
0
投稿

猜你喜欢

  • python集合比较(交集,并集,差集)方法详解

    2023-09-30 22:11:13
  • php实现将数组或对象写入到文件的方法小结【三种方法】

    2023-11-19 05:08:04
  • 用javascript实现select的美化

    2007-05-11 16:50:00
  • HTML编辑器FCKeditor使用详解

    2010-02-28 12:30:00
  • 使用cmd命令行窗口操作SqlServer的方法

    2012-07-21 14:24:06
  • 美化段落文本 1

    2008-05-15 12:24:00
  • asp下几种常用排序算法

    2011-04-18 10:33:00
  • Python库skimage绘制二值图像代码实例

    2023-06-12 15:05:33
  • ASP同一站点下gb2312和utf-8页面传递参数乱码的终极解决方法

    2011-02-20 11:00:00
  • 推荐:怎么用javascript进行拖拽

    2007-09-21 20:14:00
  • 用CSS实现柱状图(Bar Graph)的方法(四)—table实现复杂柱状图

    2008-05-28 12:55:00
  • 分享PHP函数实现数字与文字分页代码

    2023-11-14 12:32:54
  • 不要犯WEB字体编辑的10种错误

    2008-08-19 12:55:00
  • dl+ol应用

    2008-06-21 17:04:00
  • MySQL如何查询当前正在运行的SQL语句

    2009-02-13 13:40:00
  • asp使用ServerVariables集合

    2008-02-27 13:22:00
  • ASP自动解压RAR文件代码

    2007-11-06 13:29:00
  • 宽屏不是用来阅读的

    2009-04-05 15:59:00
  • asp内置对象ObjectContext详解

    2007-09-18 13:16:00
  • Python如何使用字符打印照片

    2023-06-12 09:20:34
  • asp之家 网络编程 m.aspxhome.com