ここでコード例を見つけました:N-QUEENバックトラッキングの問題が解決しました
これはこのコードを示しています:
#include <iostream>
using namespace std;
/** this is the size of chess board */
#define N 8
/** Given a completed board, this prints it to the stdout */
void print_solution(int state[N][N])
{
int i,j;
for (i = 0; i < N; ++i)
{
for (j = 0; j < N; ++j)
cout << state[i][j] << " ";
cout << endl;
}
cout << endl;
}
/** return true if placing a queen on [row][col] is acceptable
else return false */
bool accept(int state[N][N], int row, int col)
{
int i,j;
/* check the column */
for (i = 0; i < N; ++i)
{
if (state[row][i])
return false;
}
/* check the row */
for (i = 0; i < N; ++i)
{
if (state[i][col])
return false;
}
/* check the upper left diagnol */
for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
{
if (state[i][j])
return false;
}
/* check the lower left diagnol */
for (i = row, j = col; i < N && j >= 0; ++i, --j)
{
if (state[i][j])
return false;
}
/* check the upper right diagnol */
for (i = row, j = col; i >= 0 && j < N; i--, ++j)
{
if (state[i][j])
return false;
}
/* check the lower right diagnol */
for (i = row, j = col; i < N && j < N; ++i, ++j)
{
if (state[i][j])
return false;
}
/* return true if all tests passed */
return true;
}
void solve_state(int state[N][N], int row)
{
int i;
/* if all queens have been placed at non conflicting positions */
if (row == N)
{
print_solution(state);
return;
}
/* Place queens on all positions in a given row and
check if the state is acceptable
Continue the process till all possibilities found */
for(i=0; i<N; ++i){
if(accept(state, row, i)){
state[row][i] = 1;
solve_state(state, row+1);
}
state[row][i] = 0;
}
}
int main()
{
/* initialise the board */
int state[N][N] = {0};
solve_state (state, 0);
return 0;
}
私は論理でかなり失敗し、再帰などを学ぶのにさらに苦労します。本当に私を悩ませているのは、なぜこのコードがチェス問題の8人の女王の92の解決策すべてをループするのか理解できないということです。最初は1つの解決策しか見つからないと思っていましたが、コードをテストして考えられるすべての解決策を実行すると、驚きました。
たった1つの解決策の後でそれを「停止」させようとしたので、ここでは非常に基本的なものが欠けているに違いありませんが、失敗します。
したがって、ここで私が求めているのは、これを理解するために、このコードを前提として、一度ループして最初の解決策を見つけたい場合、何を変更する必要があるかということだと思います。どんな魔術がこのことをいつもループさせているのか?!