我知道这有点长,但你知道为什么我的 8 皇后算法不返回任何东西吗?我创建了一个空板,类似的邻居板和皇后(用于跟踪它们的位置)我为每一列放置一个皇后并将它们放入随机行然后我计算总碰撞然后我将皇后放在其他行(在同一列) 并再次计算总碰撞。之后,我找到了会产生最小碰撞的位置,直到我用完可以最小化碰撞的位置,并且在打破第一个(计算邻居碰撞)循环之后,我打破了第二个循环(重置所有皇后位置)如果碰撞为 0。
import random
from array import array
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]]
neighbour = [[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]]
queens = [0,0,0,0,0,0,0,0]
def collision_count(column,row):
coll = 0
for j in range(8):
if j == row:
continue
if board[column][j] == 1 :
coll += 1
while(column < 7 and row < 7):
row += 1
column +=1
if board[column][row] == 1:
coll += 1
while(column > 0 and row > 0):
row -= 1
column -=1
if board[column][row] == 1:
coll += 1
while(column > 0 and row < 7):
row += 1
column -=1
if board[column][row] == 1:
coll += 1
while(column < 7 and row > 0):
row -= 1
column +=1
if board[column][row] == 1:
coll += 1
return coll
def totalcoll():
totcoll = 0
for i in range(8):
totcoll += collision_count(i,queens[i])
return totcoll
while True:
for i in range(8):
queens[i] = random.randrange(0,8)
board[i][queens[i]] = 1
totalcollision = totalcoll()
while True:
for i in range(8):
oldqueen = queens[i]
for j in range(8):
queens[i] = j
neighbour[i][j] = totalcoll()
queens[i] = oldqueen
min = neighbour[0][0]
minqueencol = 0
minqueenrow = 0
for i in range(8):
for j in range(8):
if(neighbour[i][j]<min):
min = neighbour[i][j]
minqueenrow = j
minqueencol = i
if min<totalcollision:
totalcollision = min
queens[minqueencol] = minqueenrow
else:
break
if totalcollision == 0:
break
print("a")
for i in range(8):
for j in range(8):
print(board[i][j])