首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >python版蛇形填数

python版蛇形填数

作者头像
py3study
发布2020-01-07 14:41:43
发布2020-01-07 14:41:43
1.6K0
举报
文章被收录于专栏:python3python3

引 入


      蛇形填数,一道经典有趣的算法入门题。这里用python来实现。

代码 vim snake.py


代码语言:javascript
复制
#!/usr/bin/env python
#-*- coding: utf-8 -*-

#矩阵初始化函数
def genMatrix(rows,cols):  
    #用二维数组来代表矩阵
    matrix = [[0 for col in range(cols)] for row in range(rows)]  
    for i in range(rows):  
        for j in range(cols):  
            matrix[i][j]
    return matrix

#构造蛇形填数函数
def testSnake():
    #调用genMatrix函数
    matrix = genMatrix(number, number)
    i = j = 0
    total = matrix[i][j] = 1
    while(total < number * number):
        #向右填数
        while(j + 1 < number and matrix[i][j + 1] == 0): 
            total += 1
            j += 1
            matrix[i][j] = total
        #向下填数
        while(i + 1 < number and matrix[i + 1][j] == 0):
            total += 1
            i += 1
            matrix[i][j] = total
        #向左填数
        while(j > 0 and matrix[i][j - 1] == 0): 
            total += 1
            j -= 1
            matrix[i][j] = total
        #向上填数
        while(i + 1 > 0 and matrix[i - 1][j] == 0): 
            total += 1
            i -= 1
            matrix[i][j] = total
    #打印显示
    for i in range(number):  
            for j in range(number):
                print ('\t%d ' % matrix[i][j]),
                #python2.X版本用print()后面加上逗号来不换行  
                #python3.X版本的打印不换行可用print ('\t%d ' % matrix[i][j], end='')
            print('\n')

#主流程控制
while True:
    number = int(raw_input("Please Input your number:"))
    if(number <= 0):
        print("请输入大于0的整数")
        continue
    testSnake()
    flag = raw_input("Do you want to continue? Y/N").strip()  
    #字符串的strip()是为了去除命令行输入前后的空格
    if(flag.__eq__("Y")):
        continue
    break

运行测试

代码语言:javascript
复制
[root@www ~]# python snake.py 
Please Input your number: -2
请输入大于0的整数
Please Input your number: 3
1         2       3       

8         9       4       

7         6       5       

Do you want to continue? Y/N: Y
Please Input your number:4
1         2       3       4       

12        13      14      5       

11        16      15      6       

10        9       8       7       

Do you want to continue? Y/N: N
[root@www ~]#

结 语


        程序=数据结构+算法,平时多多编写有趣的算法题,既能锻炼解决问题的能力,又能熟悉python相关语法,何乐而不为呢?

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/09/18 ,如有侵权请联系 cloudcommunity@tencent.com 删除
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档