可以使用树搜索的方法做,也可以用回溯递归算法来做。
在八皇后问题中,我们首先选择第一个皇后的位置。一旦选定位置,就会排除同行、同列和同斜线上的位置。接下来,我们放置第二个皇后,只能选择未被第一个皇后影响的位置。随后,放置第三个皇后,同样不能放在前两个皇后的影响范围内的位置。如果此时没有可选的位置了,意味着当前布局不可行,需要回退到上一步。在回退时,重新选择第二个皇后的位置,确保她不受第一个皇后的影响,然后再尝试放置第三个皇后。如果仍然找不到可行位置,再次回退到选择第二个皇后的步骤。如果第二个皇后也没有更多可选的位置,就回退到第一个皇后,重新选择她的位置,重新进行布局的尝试。
Python-八皇后代码
def queen_try(i, row_pos, col, left_diag, right_diag):
if i == 8:
display(row_pos)
return
if i <= 7:
for j in range(8):
if col[j] == 0 and left_diag[i + j] == 0 and right_diag[i - j + 7] == 0:
row_pos[i] = j
col[j] = 1
left_diag[i + j] = 1
right_diag[i - j + 7] = 1
queen_try(i+1, row_pos, col, left_diag, right_diag)
col[j] = 0
left_diag[i + j] = 0
right_diag[i - j + 7] = 0
sum = 1
queen_try(0, name.row_pos, name.col, name.left_diag, name.right_diag)
print(f'The Total Solution Number is {sum-1}')
Python-N皇后代码(原理相同)
def queen_try(i, row_pos, col, left_diag, right_diag):
if i == n:
display(row_pos)
return
if i <= n - 1:
for j in range(n):
if col[j] == 0 and left_diag[i + j] == 0 and right_diag[i - j + n - 1] == 0:
row_pos[i] = j
col[j] = 1
left_diag[i + j] = 1
right_diag[i - j + n - 1] = 1
queen_try(i+1, row_pos, col, left_diag, right_diag)
col[j] = 0
left_diag[i + j] = 0
right_diag[i - j + n - 1] = 0
n = input("The Queen Number is :")
n = int(n)
sum = 1
class name:
row_pos = [0] * n
col = [0] * n
left_diag = [0] * 2 * n
right_diag = [0] * 2 * n
queen_try(0, name.row_pos, name.col, name.left_diag, name.right_diag)
print(f'The Total Solution Number is {sum-1}')
C++-8皇后代码(原理相同)
#include<iostream>
using namespace std;
int sum = 0;
void queen_try(int i,int row_pos[],int col[],int left_diag[],int right_diag[])
{
if(i < 8)
{
for(int j = 0;j < 8; j++)
{
if(col[j] == 0 && left_diag[i + j] == 0 && right_diag[i - j +7] == 0)
{
row_pos[i] = j;
col[j] = 1;
left_diag[i + j] = 1;
right_diag[i - j +7] = 1;
queen_try(i+1, row_pos, col, left_diag, right_diag);
col[j] = 0;
left_diag[i + j] = 0;
right_diag[i - j +7] = 0;
}
}
}
if(i == 8)
{
display(row_pos);
return;
}
}
int main()
{
int n = 8;
int row_pos[n] = {0};
int col[n] = {0};
int left_diag[2*n] = {0};
int right_diag[2*n] = {0};
queen_try(0, row_pos, col, left_diag, right_diag);
cout<<"The Total Solution Number is: "<<sum<<endl;
}