想了想,没啥说的,代码不算难,涉及到的知识点本文都有说明:

#八皇后问题

board=[

[0,0,0,0,0,0,0,0],

[0,0,0,0,0,0,0,0],

[0,0,0,0,0,0,0,0],

[0,0,0,0,0,0,0,0],

[0,0,0,0,0,0,0,0],

[0,0,0,0,0,0,0,0],

[0,0,0,0,0,0,0,0],

[0,0,0,0,0,0,0,0]

]

 

total=0;

 

def can_play(x,y):

#判断(xy)坐标能否放皇后

#1.判断x行是否有皇后

for i in range(0,y):

if board[x][i]==1:

return False

#2.判断y列是否有皇后

for i in range(0,x):

if board[i][y]==1:

return False

#3.判断左斜是否有皇后

for i in range(0,x):

if x+y-i <= 7 and board[i][x+y-i]==1:

return False

#4.判断右斜是否有皇后

for index,i in enumerate(range(x-1,-1,-1)):

s_y=y-(index+1)

if s_y >= 0:

if board[i][s_y]==1:

return False


return True

 

def print_board():

for i in range(8):

for j in range(8):

if board[i][j]==0:

function(){ //技术指标 http://www.fx61.com/faq/muniu/437.html

print("",end=" ")   #print()函数中加一个“空格(end=" ")”,表示不换行

else:

print("",end=" ")

print()

 

def put_queen(step):

if step==8:

print_board()

global total

total += 1

print("------------------------")

else:

for i in range(8):

#判断该位置是否能放当前皇后

if can_play(step,i):

#1.设置现场

board[step][i]=1

#2.开始递归

put_queen(step+1)

#3.恢复现场   (非常重要!前面的走,后面的要恢复)

board[step][i]=0

 

if __name__ == "__main__":

print_board(0)       #从第0步开始走

print("总共有{}种方法".format(total))   #Python的变量输出格式:{} + format()

rangePython的一个内置函数,其作用是遍历其中区间中的所有值,遵循左闭右开原则