TheAlgorithms-C-Plus-Plus/backtracking/n_queens.cpp

72 lines
1.5 KiB
C++
Raw Normal View History

2019-08-21 10:10:08 +08:00
#include <iostream>
2017-04-23 15:47:42 +08:00
#define N 4
using namespace std;
void printSolution(int board[N][N])
{
2019-08-21 10:10:08 +08:00
cout << "\n";
2017-04-23 15:47:42 +08:00
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++) cout << "" << board[i][j];
2019-08-21 10:10:08 +08:00
cout << "\n";
2017-04-23 15:47:42 +08:00
}
}
bool isSafe(int board[N][N], int row, int col)
{
int i, j;
2019-08-21 10:10:08 +08:00
2017-04-23 15:47:42 +08:00
/* Check this row on left side */
for (i = 0; i < col; i++)
if (board[row][i])
return false;
2019-08-21 10:10:08 +08:00
2017-04-23 15:47:42 +08:00
/* Check upper diagonal on left side */
2019-08-21 10:10:08 +08:00
for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
2017-04-23 15:47:42 +08:00
if (board[i][j])
return false;
2019-08-21 10:10:08 +08:00
2017-04-23 15:47:42 +08:00
/* Check lower diagonal on left side */
2019-08-21 10:10:08 +08:00
for (i = row, j = col; j >= 0 && i < N; i++, j--)
2017-04-23 15:47:42 +08:00
if (board[i][j])
return false;
2019-08-21 10:10:08 +08:00
2017-04-23 15:47:42 +08:00
return true;
}
void solveNQ(int board[N][N], int col)
{
2019-08-21 10:10:08 +08:00
if (col >= N)
{
2017-04-23 15:47:42 +08:00
printSolution(board);
return;
}
2019-08-21 10:10:08 +08:00
2017-04-23 15:47:42 +08:00
/* Consider this column and try placing
this queen in all rows one by one */
for (int i = 0; i < N; i++)
{
/* Check if queen can be placed on
board[i][col] */
2019-08-21 10:10:08 +08:00
if (isSafe(board, i, col))
2017-04-23 15:47:42 +08:00
{
/* Place this queen in board[i][col] */
2019-08-21 10:10:08 +08:00
// cout<<"\n"<<col<<"can place"<<i;
2017-04-23 15:47:42 +08:00
board[i][col] = 1;
2019-08-21 10:10:08 +08:00
2017-04-23 15:47:42 +08:00
/* recur to place rest of the queens */
solveNQ(board, col + 1);
board[i][col] = 0; // BACKTRACK
2017-04-23 15:47:42 +08:00
}
}
}
2019-08-21 10:10:08 +08:00
2017-04-23 15:47:42 +08:00
int main()
{
int board[N][N] = {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}};
2019-08-21 10:10:08 +08:00
solveNQ(board, 0);
2017-04-23 15:47:42 +08:00
return 0;
}