P1219 [USACO1.5] 八皇后 Checker Challenge - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
python
n = int(input())
a = [0 for _ in range(1,2*n+100)] #标记行
b = [0 for _ in range(1,2*n+100)] #标记列
c = [0 for _ in range(1,2*n+100)] #标记左下到右上的对角线
d = [0 for _ in range(1,2*n+100)] #标记左上到右下的对角线
sum = 0
def printf():
global sum
if sum <=2:
for i in range(1,n+1):
print(a[i],end=' ')
print('\n',end='')
sum += 1
def dfs(i):
for j in range(1,n+1):
# if i+j<n+1 and abs(i-j)<n+1 :
if b[j] == 0 and d[i-j+n] == 0 and c[i+j]==0:
a[i] = j
b[j] = 1
c[i + j] = 1
d[i-j+n] = 1
dfs(i+1)
b[j] = 0
c[i + j] = 0
d[i-j+n] = 0
if i==n :
printf()
return
dfs(1)
print(sum)
不知道该怎么优化了,输入13,这个案例跑起来超时了。