2019-12-27 19:27:24 +08:00
|
|
|
#include <iostream>
|
|
|
|
#define n 4
|
|
|
|
|
2020-05-30 07:26:30 +08:00
|
|
|
void PrintSol(int Board[n][n])
|
|
|
|
{
|
|
|
|
for (int i = 0; i < n; i++)
|
|
|
|
{
|
|
|
|
for (int j = 0; j < n; j++)
|
|
|
|
{
|
2019-12-27 19:27:24 +08:00
|
|
|
std::cout << Board[i][j] << " ";
|
|
|
|
}
|
|
|
|
std::cout << std::endl;
|
|
|
|
}
|
|
|
|
std::cout << std::endl;
|
|
|
|
}
|
|
|
|
|
2020-05-30 07:26:30 +08:00
|
|
|
bool CanIMove(int Board[n][n], int row, int col)
|
|
|
|
{
|
2019-12-27 19:27:24 +08:00
|
|
|
/// check in the row
|
2020-05-30 07:26:30 +08:00
|
|
|
for (int i = 0; i < col; i++)
|
|
|
|
{
|
2019-12-27 19:27:24 +08:00
|
|
|
if (Board[row][i] == 1)
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
/// check the first diagonal
|
2020-05-30 07:26:30 +08:00
|
|
|
for (int i = row, j = col; i >= 0 && j >= 0; i--, j--)
|
|
|
|
{
|
2019-12-27 19:27:24 +08:00
|
|
|
if (Board[i][j] == 1)
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
/// check the second diagonal
|
2020-05-30 07:26:30 +08:00
|
|
|
for (int i = row, j = col; i <= n - 1 && j >= 0; i++, j--)
|
|
|
|
{
|
2019-12-27 19:27:24 +08:00
|
|
|
if (Board[i][j] == 1)
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2020-05-30 07:26:30 +08:00
|
|
|
void NQueenSol(int Board[n][n], int col)
|
|
|
|
{
|
|
|
|
if (col >= n)
|
|
|
|
{
|
2019-12-27 19:27:24 +08:00
|
|
|
PrintSol(Board);
|
|
|
|
return;
|
|
|
|
}
|
2020-05-30 07:26:30 +08:00
|
|
|
for (int i = 0; i < n; i++)
|
|
|
|
{
|
|
|
|
if (CanIMove(Board, i, col))
|
|
|
|
{
|
2019-12-27 19:27:24 +08:00
|
|
|
Board[i][col] = 1;
|
|
|
|
NQueenSol(Board, col + 1);
|
|
|
|
Board[i][col] = 0;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-05-30 07:26:30 +08:00
|
|
|
int main()
|
|
|
|
{
|
2019-12-27 19:27:24 +08:00
|
|
|
int Board[n][n] = {0};
|
|
|
|
NQueenSol(Board, 0);
|
|
|
|
}
|