File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ // link https://leetcode.com/problems/n-queens/
2+
3+ // Approach : We use a recursive backtracking approach to solve
4+ // this problem
5+
6+ // To get the intuition behind the solution Watch this video
7+ // https://youtu.be/Ph95IHmRp5M
8+
9+ import java .util .List ;
10+ import java .util .ArrayList ;
11+ class NQueens {
12+ public List <List <String >> solveNQueens (int n ) {
13+
14+ List <List <String >> l = new ArrayList <List <String >>();
15+ int a [] = new int [n ];
16+
17+ findNQueens (l ,n ,0 ,a );
18+ return l ;
19+
20+ }
21+
22+ public void findNQueens (List <List <String >> l , int n , int k , int a [])
23+ {
24+ if (k == n )
25+ {
26+ List <String > board = new ArrayList <String >();
27+ for (int row = 0 ; row < n ; row ++)
28+ {
29+ StringBuilder sb = new StringBuilder (n );
30+ for (int col = 0 ; col < n ; col ++)
31+ {
32+ if (col == a [row ])
33+ {
34+ sb .append ("Q" );
35+ }
36+ else
37+ {
38+ sb .append ("." );
39+ }
40+ }
41+ board .add (sb .toString ());
42+
43+ }
44+ l .add (board );
45+ }
46+
47+ for (int i = k ; i < n ; i ++)
48+ {
49+ for (int j = 0 ; j < n ; j ++)
50+ {
51+
52+ if (isValid (i ,j ,a ))
53+ {
54+ //System.out.println(i + " " + j);
55+ a [i ] = j ;
56+ findNQueens (l ,n ,i +1 ,a );
57+ }
58+ }
59+ return ;
60+ }
61+ }
62+
63+ public boolean isValid (int i , int j , int a [])
64+ {
65+ for (int k = 0 ; k < i ; k ++)
66+ {
67+ int diff = j - a [k ];
68+ if (a [k ] == j || i - k == diff || i - k == -diff )
69+ {
70+ return false ;
71+ }
72+ }
73+ return true ;
74+ }
75+ }
You can’t perform that action at this time.
0 commit comments