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

yipeiwu_com5年前Python基础

本文实例讲述了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("【听图阁-专注于Python设计】测试结果:")
print helixMatrix(5)

运行结果:

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数据结构与算法教程》、《Python加密解密算法与技巧总结》、《Python编码操作技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

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

相关文章

Python字典循环添加一键多值的用法实例

循环写入字典key、value、删除指定的键值对: 原文本‘jp_url.txt'每行元素以逗号分隔: host_key,product_id,product_name,cont_s...

wxPython实现整点报时

本文实例为大家分享了wxPython整点报时的具体代码,供大家参考,具体内容如下 # C盘要有个wav文件,内含报时音频 import wx import...

python 获得任意路径下的文件及其根目录的方法

似乎有一段时间没有更新博客了,这里就写点小功能,轻松获得电脑任意路径下的文件及文件夹,并将其写入word,以下是主要代码: **import os** **from os impor...

python实现数通设备tftp备份配置文件示例

  环境:【wind2003[open Tftp server] + virtualbox:ubuntn10 server】tftp : Open TFTP Server&nb...

python中 ? : 三元表达式的使用介绍

(1) variable = a if exper else b(2)variable = (exper and [b] or [c])[0](2) variable = exper a...