1
+ // 52. N-Queens II
2
+ // The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other.
3
+ // Given an integer n, return the number of distinct solutions to the n-queens puzzle.
4
+ // Example 1:
5
+ // Input: n = 4
6
+ // Output: 2
7
+ // Explanation: There are two distinct solutions to the 4-queens puzzle as shown.
8
+ // Example 2:
9
+ // Input: n = 1
10
+ // Output: 1
11
+
12
+ // Constraints:
13
+ // 1 <= n <= 9
14
+
15
+ public class Solution {
16
+ public int TotalNQueens ( int n ) {
17
+ List < IList < String > > result = new List < IList < String > > ( ) ;
18
+ List < String > board = new List < String > ( ) ;
19
+ for ( int i = 0 ; i < n ; i ++ ) {
20
+ StringBuilder row = new StringBuilder ( "" ) ;
21
+ for ( int j = 0 ; j < n ; j ++ )
22
+ row . Append ( "." ) ;
23
+ board . Add ( row . ToString ( ) ) ;
24
+ }
25
+ PlaceQueen ( result , board , 0 ) ;
26
+ return result . Count ;
27
+ }
28
+ private void PlaceQueen ( List < IList < String > > result , List < String > board ,
29
+ int rowIdx )
30
+ {
31
+ if ( rowIdx == board . Count ) {
32
+ result . Add ( new List < String > ( board ) ) ;
33
+ return ;
34
+ }
35
+ for ( int i = 0 ; i < board . Count ; i ++ ) {
36
+ if ( IsSafe ( board , rowIdx , i ) ) {
37
+ StringBuilder newRow = new StringBuilder ( board [ rowIdx ] ) ;
38
+ newRow [ i ] = 'Q' ;
39
+ board [ rowIdx ] = newRow . ToString ( ) ;
40
+ PlaceQueen ( result , board , rowIdx + 1 ) ;
41
+ newRow [ i ] = '.' ;
42
+ board [ rowIdx ] = newRow . ToString ( ) ;
43
+ }
44
+ }
45
+ }
46
+ private bool IsSafe ( List < String > board , int row , int col ) {
47
+ for ( int i = row ; i >= 0 ; i -- ) {
48
+ if ( board [ i ] [ col ] == 'Q' )
49
+ return false ;
50
+ }
51
+ for ( int i = row , j = col ; i >= 0 && j >= 0 ; i -- , j -- ) {
52
+ if ( board [ i ] [ j ] == 'Q' )
53
+ return false ;
54
+ }
55
+ for ( int i = row , j = col ; i >= 0 && j < board . Count ; i -- , j ++ ) {
56
+ if ( board [ i ] [ j ] == 'Q' )
57
+ return false ;
58
+ }
59
+ return true ;
60
+ }
61
+ }
0 commit comments