先用最笨的窮舉法求解,有空再研究更好的解法:
#-*- coding: gb2312 -*-
size =8
#棋盤大小
empty ="
o"#空位
queen ="
x"#皇后
#檢視棋盤的資訊
defshow_board(cols):
fori
inrange(
1, size +1
):for
j in
range(
1, size +1
):if
j ==
cols[i]:
queen,
else
empty,
print"\n
",#檢測棋盤上皇后擺法是否合法
#return:
#true(不衝突), false(有衝突)
defcheck_board(cols):
fori
inrange(
1, size):
forj
inrange(i +1
, size +1
):if
(j -
i) ==
abs(cols[j]
-cols[i]):
return
false
return
true
solve_count =0
fora
inrange(
1, size +1
):for
b in
range(
1, size +1
):for
c in
range(
1, size +1
):for
d in
range(
1, size +1
):for
e in
range(
1, size +1
):for
f in
range(
1, size +1
):for
g in
range(
1, size +1
):for
h in
range(
1, size +1
):if
a <>
b and
a <>
c and
a <>
d and
a <>
e and
a <>
f and
a <>
g and
a <>
h and
b <>
c and
b <>
d and
b <>
e and
b <>
f and
b <>
g and
b <>
h and
c <>
d and
c <>
e and
c <>
f and
c <>
g and
c <>
h and
d <>
e and
d <>
f and
d <>
g and
d <>
h and
e <>
f and
e <>
g and
e <>
h and
f <>
g and
f <>
h and
g <>
h:cols
=[0,a,b,c,d,e,f,g,h]
ifcheck_board(cols):
solve_count +=1
show_board(cols)
print"\n
"found %i solves."%
solve_count
寫了乙個八皇后解法
先用最笨的窮舉法求解,有空再研究更好的解法 coding gb2312 size 8 棋盤大小 empty o 空位 queen x 皇后 檢視棋盤的資訊 defshow board cols fori inrange 1,size 1 for j in range 1,size 1 if j co...
八皇后問題詳細解法
問題描述 在 8 8的棋盤上,放置8個 皇后 棋子 使兩兩之 間互不攻擊。所謂互不攻擊是說任何兩個皇后都要滿足 1 不在棋盤的同一行 2 不在棋盤的同一列 3 不在棋盤的同一對角線上。求 這8個皇后中的每乙個 應該擺放在哪一列。演算法分析 陣列 column down up 分別用來標記衝突,col...
另類的八皇后求解法
heckboard.h pragma once class checkboard heckboard.cpp include stdafx.h include heckboard.h checkboard checkboard void cout 0 初始化棋盤,使得每列只有乙個棋子 checkbo...