1+ public class Solution
2+ {
3+ public int TotalNQueens ( int n )
4+ {
5+ List < int > col = new List < int > ( n ) ;
6+ List < int > diag1 = new List < int > ( n ) ;
7+ List < int > diag2 = new List < int > ( n ) ;
8+ int output = 0 ;
9+ Backtrack ( ref output , col , diag1 , diag2 , n , 0 , n ) ;
10+ return output ;
11+ }
12+
13+ private void Backtrack ( ref int output , List < int > col , List < int > diag1 , List < int > diag2 , int grid_size , int row , int queens_left )
14+ {
15+ if ( queens_left == 0 )
16+ {
17+ output ++ ;
18+ }
19+ else
20+ {
21+ for ( int c = 0 ; c < grid_size ; c ++ )
22+ {
23+ if ( CanPlace ( col , diag1 , diag2 , row , c ) )
24+ {
25+ Place ( col , diag1 , diag2 , row , c ) ;
26+ Backtrack ( ref output , col , diag1 , diag2 , grid_size , row + 1 , queens_left - 1 ) ;
27+ Remove ( col , diag1 , diag2 , row , c ) ;
28+ }
29+ }
30+ }
31+ }
32+ private bool CanPlace ( List < int > col , List < int > diag1 , List < int > diag2 , int r , int c )
33+ {
34+ return ! col . Contains ( c ) && ! diag1 . Contains ( r + c ) && ! diag2 . Contains ( r - c ) ;
35+ }
36+ private void Place ( List < int > col , List < int > diag1 , List < int > diag2 , int r , int c )
37+ {
38+ col . Add ( c ) ;
39+ diag1 . Add ( r + c ) ;
40+ diag2 . Add ( r - c ) ;
41+ }
42+ private void Remove ( List < int > col , List < int > diag1 , List < int > diag2 , int r , int c )
43+ {
44+ col . Remove ( c ) ;
45+ diag1 . Remove ( r + c ) ;
46+ diag2 . Remove ( r - c ) ;
47+ }
48+ }
0 commit comments