Skip to content

Commit 8c98397

Browse files
Merge pull request #198 from Venkatesh-24/master
Added NQueens Leetcode Solution
2 parents 2478603 + 4c166e0 commit 8c98397

1 file changed

Lines changed: 81 additions & 0 deletions

File tree

LeetCode/NQueens.java

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
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 then it means we have successfully placed all
25+
// the N Queens so we add it to the resultant list
26+
if(k == n)
27+
{
28+
List<String> board = new ArrayList<String>();
29+
for(int row = 0; row < n; row++)
30+
{
31+
StringBuilder sb = new StringBuilder(n);
32+
for(int col = 0; col < n; col++)
33+
{
34+
if(col == a[row])
35+
{
36+
sb.append("Q");
37+
}
38+
else
39+
{
40+
sb.append(".");
41+
}
42+
}
43+
board.add(sb.toString());
44+
45+
}
46+
l.add(board);
47+
}
48+
49+
// The for loop traverses the entire matrix placing each
50+
// queen at a position and checking if it is valid
51+
for(int i = k; i < n; i++)
52+
{
53+
for(int j = 0; j < n; j++)
54+
{
55+
56+
if(isValid(i,j,a))
57+
{
58+
//System.out.println(i + " " + j);
59+
a[i] = j;
60+
findNQueens(l,n,i+1,a);
61+
}
62+
}
63+
return;
64+
}
65+
}
66+
67+
//This function checks whether placing Queen at a particular
68+
// position affects previously placed Queens
69+
public boolean isValid(int i, int j, int a[])
70+
{
71+
for(int k = 0; k < i; k++)
72+
{
73+
int diff = j - a[k];
74+
if(a[k] == j || i - k == diff || i - k == -diff)
75+
{
76+
return false;
77+
}
78+
}
79+
return true;
80+
}
81+
}

0 commit comments

Comments
 (0)