import time
p=1
t1=0
a=0
class solution(object):
def queens_num(self, n): #矩阵为n行n列
global T1
T1 = time.perf_counter()
global t1
t1 = time.perf_counter()
self.position([-1] * n, 0, n)
def position(self, col, row, n): #row:当前行,col:每一行皇后的位置 n为总行数
global a
if row == n:
global p
p+=1
global a
if a==0:
print(a)
global t2
t2 =time.perf_counter()
self.printSolution(col, n) #到最后一行,打印结果
global t1
t1 = time.perf_counter()
return
for row_position in range(n):
col[row] = row_position #row_position皇后所在列的位置
if self.isValid(col, row):
self.position(col, row + 1, n)
def isValid(self, col, row):
if len(set(col[:row + 1])) != len(col[:row + 1]): #检查列
return False
for i in range(row): #检查对角线
if abs(col[i] - col[row]) == int(row - i):
return False
return True
def printSolution(self, col, n):
global p
global t2
global t1
# print(t1)
# print(t2)
if 0.001<(t2 - t1) and (t2 - t1)<1:
print('Solution%d,用时:%s毫秒' % (p,(t2 - t1)*1000))
elif (t2 - t1)>1 and (t2 - t1)<60:
print('Solution%d,用时:%s秒' % (p,(t2 - t1)))
elif (t2 - t1)<0.001:
print('Solution%d,用时:%s1微秒' % ((p,(t2 - t1)*1000000)))
t1=0
t2=0
splitline = ""
for column in range(n):
splitline +="----"
splitline +="-"
print(splitline)
for row in range(n):
line = ""
splitline = ""
for column in range(n):
if col[row] == column:
line += "| Q "
splitline +="----"
else:
line += "| * "
splitline +="----"
line += "|"
splitline +="-"
print(line)
print(splitline)
print('\n')
def main():
count0 = input("请输入N皇后:")
while True:
if count0.isdigit():
m=int(count0)
if m>0:
break
else:
count0 = input("请重新输入:")
else:
count0 = input("请重新输入:")
while True:
str = input("是否需要打印所有结果,需要Y;不需要N: ")
if str=='Y' or str=='y':
print("打印所有结果")
break
elif str=='N'or str=='n':
global a
a=1
print("只输出解法数")
break
else:
print("请重新输入")
q = solution()
q.queens_num(m)
print("Total solutions:",p-1)
T2 = time.perf_counter()
# print(T1)
# print(T2)
if 0.001<(T2 - T1)<1:
print('整体用时:%s毫秒' % ((T2 - T1)*1000))
elif (T2 - T1)>1 and (T2 - T1)<60:
print('整体用时:%s秒' % ((T2 - T1)))
elif (T2 - T1)<0.001:
print('整体用时小于1微秒')
if __name__ == '__main__':
main()