引 入
蛇形填数,一道经典有趣的算法入门题。这里用python来实现。
代码 vim snake.py
#!/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
运行测试
[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相关语法,何乐而不为呢?
附:如对上面描述有疑问,期待与朋友您共同探讨。本人QQ:1084569767