-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathN_Queen.cpp
More file actions
51 lines (51 loc) · 1.33 KB
/
N_Queen.cpp
File metadata and controls
51 lines (51 loc) · 1.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <bits/stdc++.h>
using namespace std;
#define n 4
void printsol(int board[n][n])
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
cout << board[i][j] << " ";
cout << "\n";
}
}
bool isvalid(int board[n][n], int row, int col) //We just need to check for the upper rows which have been filled before this
{
//To check vertically in a particular column
for (int i = 0; i < row; i++)
if (board[i][col])
return false;
//To check upper diagonal towards the right
for (int i = row, j = col; i > 0 && j < n; i--, j++)
if (board[i][j])
return false;
//To check upper diagonal towards the left
for (int i = row, j = col; i > 0 && j > 0; i--, j--)
if (board[i][j])
return false;
return true;
}
bool solverow(int board[n][n], int row)
{
if (row == n)
return true;
for (int col = 0; col < n; col++)
if (isvalid(board, row, col))
{
board[row][col] = 1;
if (solverow(board, row + 1))
return true;
board[row][col] = 0; //Backtracking for a wrong ans
}
return false; //Backtracking
}
int main()
{
int board[n][n] = {0};
if (solverow(board, 0))
printsol(board);
else
cout << "No Solution Exists";
return 0;
}