八皇后问题的 Python 解法和多维数组的初始化
February 26th, 2010
No comments
以前用 Python 写过一个八皇后的小程序,遇到过一个多维数组初始化的问题,现在整理出来。
首先是八皇后问题的解决:
#
#Author:leeing
#Version:Python 3.1.1
#License:GPL V3
chess=[[0 for col in range(8)] for row in range(8)]
pos =0
i=0
flag =0
def check(i,pos):
if i==0:
return True
for counter in range(i):
if chess[counter][pos]==1:
return False
for x in range(min(i,pos)):
if chess[i-x-1][pos-x-1]==1:
return False
if pos<7:
for y in range(min(i,7-pos)):
if chess[i-y-1][pos+y+1]==1:
return False
return True
while i<8:
chess[i][pos]=1
if check(i,pos):
i=i+1
pos=0
else:
chess[i][pos]=0
while pos<7 and not check(i,pos):
pos=pos+1
if pos<=7 and check(i,pos):
chess[i][pos]=1
i=i+1
pos=0
else:
if (chess[i-1].index(1))<7:
pos = chess[i-1].index(1)+1
chess[i-1][pos-1]=0
i=i-1
else:
if i>=2:
pos =chess[i-2].index(1)+1
chess[i-1][7]=0
chess[i-2][pos-1]=0
i=i-2
else:
break
if 1 in chess[7]:
flag=flag+1
print(str(flag)+" found:")
for k in range(len(chess)):
print(chess[k])
print("\n"+"*"*25)
if (chess[7].index(1))<7:
pos = chess[7].index(1)+1
chess[7][pos-1]=0
i=7
else:
pos =chess[6].index(1)+1
chess[7][7]=0
chess[6][pos-1]=0
i=6
print ("八皇后问题共有 "+ str(flag) + " 个解。")
运行结果如下:
..... ..... 91 found: [0, 0, 0, 0, 0, 0, 0, 1] [0, 0, 1, 0, 0, 0, 0, 0] [1, 0, 0, 0, 0, 0, 0, 0] [0, 0, 0, 0, 0, 1, 0, 0] [0, 1, 0, 0, 0, 0, 0, 0] [0, 0, 0, 0, 1, 0, 0, 0] [0, 0, 0, 0, 0, 0, 1, 0] [0, 0, 0, 1, 0, 0, 0, 0] ************************* 92 found: [0, 0, 0, 0, 0, 0, 0, 1] [0, 0, 0, 1, 0, 0, 0, 0] [1, 0, 0, 0, 0, 0, 0, 0] [0, 0, 1, 0, 0, 0, 0, 0] [0, 0, 0, 0, 0, 1, 0, 0] [0, 1, 0, 0, 0, 0, 0, 0] [0, 0, 0, 0, 0, 0, 1, 0] [0, 0, 0, 0, 1, 0, 0, 0] ************************* 八皇后问题共有 92 个解。

评论