引 入
蛇形填数,一道经典有趣的算法入门题。这里用python来实现。
代码 vim snake.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
| #!/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[j]
return matrix
#构造蛇形填数函数
def testSnake():
#调用genMatrix函数
matrix = genMatrix(number, number)
i = j = 0
total = matrix[j] = 1
while(total < number * number):
#向右填数
while(j + 1 < number and matrix[j + 1] == 0):
total += 1
j += 1
matrix[j] = total
#向下填数
while(i + 1 < number and matrix[i + 1][j] == 0):
total += 1
i += 1
matrix[j] = total
#向左填数
while(j > 0 and matrix[j - 1] == 0):
total += 1
j -= 1
matrix[j] = total
#向上填数
while(i + 1 > 0 and matrix[i - 1][j] == 0):
total += 1
i -= 1
matrix[j] = total
#打印显示
for i in range(number):
for j in range(number):
print ('\t%d ' % matrix[j]),
#python2.X版本用print()后面加上逗号来不换行
#python3.X版本的打印不换行可用print ('\t%d ' % matrix[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
|
运行测试
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
| [iyunv@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
[iyunv@www ~]#
|
结 语
程序=数据结构+算法,平时多多编写有趣的算法题,既能锻炼解决问题的能力,又能熟悉python相关语法,何乐而不为呢?
|