File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change 1+ class  Solution  {
2+  public  int  totalNQueens (int  n ) {
3+  if  (n  == 0 ) {
4+  return  0 ;
5+  }
6+ 
7+  char [][] board  = new  char [n ][n ];
8+  for  (int  i  = 0 ; i  < n ; i ++) {
9+  for  (int  j  = 0 ; j  < n ; j ++) {
10+  board [i ][j ] = '.' ;
11+  }
12+  }
13+ 
14+  int [] result  = new  int [1 ];
15+  dfs (board , 0 , result );
16+  return  result [0 ];
17+  }
18+ 
19+  private  boolean  isValid (char [][] board , int  row , int  col ) {
20+  for  (int  i  = 0 ; i  < board .length ; i ++) {
21+  for  (int  j  = 0 ; j  < board [i ].length ; j ++) {
22+  if  (board [i ][j ] == 'Q'  && (row  == i  || row  + j  == col  + i  || row  + col  == i  + j )) {
23+  return  false ;
24+  }
25+  }
26+  }
27+ 
28+  return  true ;
29+  }
30+ 
31+  private  void  dfs (char [][] board , int  colIdx , int [] result ) {
32+  if  (colIdx  == board .length ) {
33+  ++result [0 ];
34+  return ;
35+  }
36+ 
37+  for  (int  i  = 0 ; i  < board .length ; i ++) {
38+  if  (isValid (board , i , colIdx )) {
39+  board [i ][colIdx ] = 'Q' ;
40+  dfs (board , colIdx  + 1 , result );
41+  board [i ][colIdx ] = '.' ;
42+  }
43+  }
44+  }
45+ }
                         You can’t perform that action at this time. 
           
                  
0 commit comments