本文实例讲述了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数据结构与算法教程》、《Python加密解密算法与技巧总结》、《Python编码操作技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》
希望本文所述对大家Python程序设计有所帮助。
标签:
Python,螺旋矩阵,填充算法
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
金钱帮资源网 Copyright www.kbjia.com
暂无“Python实现螺旋矩阵的填充算法示例”评论...
更新日志
2024年10月07日
2024年10月07日
- 群星《前途海量 电影原声专辑》[FLAC/分轨][227.78MB]
- 张信哲.1992-知道新曲与精丫巨石】【WAV+CUE】
- 王翠玲.1995-ANGEL【新艺宝】【WAV+CUE】
- 景冈山.1996-我的眼里只有你【大地唱片】【WAV+CUE】
- 群星《八戒 电影原声带》[320K/MP3][188.97MB]
- 群星《我的阿勒泰 影视原声带》[320K/MP3][139.47MB]
- 纪钧瀚《胎教古典音乐 钢琴与大提琴的沉浸时光》[320K/MP3][148.91MB]
- 刘雅丽.2001-丽花皇后·EMI精选王【EMI百代】【FLAC分轨】
- 齐秦.1994-黄金十年1981-1990CHINA.TOUR.LIVE精丫上华】【WAV+CUE】
- 群星.2008-本色·百代音乐人创作专辑【EMI百代】【WAV+CUE】
- 群星.2001-同步过冬AVCD【环球】【WAV+CUE】
- 群星.2020-同步过冬2020冀待晴空【环球】【WAV+CUE】
- 沈雁.1986-四季(2012梦田复刻版)【白云唱片】【WAV+CUE】
- 纪钧瀚《胎教古典音乐 钢琴与大提琴的沉浸时光》[FLAC/分轨][257.88MB]
- 《国语老歌 怀旧篇 3CD》[WAV/分轨][1.6GB]