File tree Expand file tree Collapse file tree 1 file changed +87
-0
lines changed
Expand file tree Collapse file tree 1 file changed +87
-0
lines changed Original file line number Diff line number Diff line change 1+ #include < iostream>
2+ #include < vector>
3+ using namespace std ;
4+
5+ bool isSafe (vector<vector<bool > > grid, int curr_row, int y, int n)
6+ {
7+ for (int row=0 ; row<curr_row; row++)
8+ {
9+ if (grid[row][y]==1 ) // checking for a row
10+ {
11+ return false ;
12+ }
13+ }
14+
15+ int row=curr_row, col=y;
16+ while (row>=0 && col>=0 )
17+ {
18+ if (grid[row][col]==1 ) // checking for upper left diagonal
19+ {
20+ return false ;
21+ }
22+ row--;
23+ col--;
24+ }
25+
26+ row=curr_row, col=y;
27+ while (row>=0 && col<=n)
28+ {
29+ if (grid[row][col]==1 ) // checking for upper right diagonal
30+ {
31+ return false ;
32+ }
33+ row--;
34+ col++;
35+ }
36+
37+ return true ;
38+ }
39+
40+ void display (vector<vector<bool > > grid, int n)
41+ {
42+ for (int i=0 ; i<n; i++)
43+ {
44+ for (int j=0 ; j<n; j++)
45+ {
46+ if (grid[i][j])
47+ cout<<" 1" ;
48+
49+ else
50+ cout<<" 0" ;
51+ }
52+ cout<<endl;
53+ }
54+ }
55+
56+ // to count the no. of solutions possible
57+ int count=0 ;
58+ void countnQueen (vector<vector<bool > > &grid, int curr_row, int n)
59+ {
60+ if (curr_row==n){
61+ count++;
62+ display (grid, n);
63+ cout<<endl;
64+ return ;
65+ }
66+
67+ for (int col=0 ; col<n; col++){
68+ if (isSafe (grid, curr_row, col, n)){
69+ grid[curr_row][col]=1 ;
70+ countnQueen (grid, curr_row+1 , n);
71+ grid[curr_row][col]=0 ; // backtracking
72+ }
73+ }
74+ }
75+
76+ int main ()
77+ {
78+ int n;
79+ cin>>n;
80+
81+ vector<vector<bool > > grid (n, vector<bool >(n, false ));
82+
83+ countnQueen (grid,0 ,n);
84+ cout<<count;
85+
86+ return 0 ;
87+ }
You can’t perform that action at this time.
0 commit comments