Skip to content

Commit f3f0754

Browse files
Merge pull request codemistic#613 from nilesh05apr/nilesh
add: N-Queen Backtrack solution
2 parents 59104e4 + 872f479 commit f3f0754

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

Java/LeetCodeN-Queens.java

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
/* Question Link: https://leetcode.com/problems/n-queens/
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 all distinct solutions to the n-queens puzzle. You may return the answer in any order.
4+
* Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space, respectively.
5+
*/
6+
7+
8+
9+
10+
11+
12+
class Solution {
13+
public List<List<String>> solveNQueens(int n) {
14+
List<List<String>> results = new ArrayList<>();
15+
if(n ==0) return results;
16+
backtrace(results, new ArrayList<String>(), 0, n, new boolean[n]);
17+
return results;
18+
}
19+
20+
public static void backtrace(List<List<String>> result, List<String> list, int level, int n, boolean[] used){
21+
if(level == n) result.add(new ArrayList<String>(list));
22+
else{
23+
for(int i = 0; i < n; i++){
24+
if(used[i]) continue;
25+
if(isValid(list, level, i, n)){
26+
list.add(createQueen(n, i));
27+
used[i] = true;
28+
backtrace(result, list, level + 1, n, used);
29+
used[i] = false;
30+
list.remove(list.size() - 1);
31+
}
32+
}
33+
}
34+
}
35+
public static boolean isValid(List<String> list, int row, int column, int n){
36+
if(row > 0){
37+
String cmp = list.get(row - 1);
38+
for(int i = 0; i < row; i++)
39+
if(list.get(i).charAt(column) == 'Q') return false;
40+
int tempRow = row;
41+
int tempCol = column;
42+
while(--tempRow >= 0 && --tempCol >= 0){
43+
if(list.get(tempRow).charAt(tempCol) == 'Q') return false;
44+
}
45+
tempRow = row;
46+
tempCol = column;
47+
while(--tempRow >= 0 && ++tempCol <= n-1)
48+
if(list.get(tempRow).charAt(tempCol) == 'Q') return false;
49+
}
50+
return true;
51+
}
52+
private static String createQueen(int n, int index){
53+
StringBuilder sb = new StringBuilder();
54+
int i = 0;
55+
for(; i < index; i++)
56+
sb.append('.');
57+
sb.append('Q');
58+
for(++i; i < n; i++){
59+
sb.append('.');
60+
}
61+
return sb.toString();
62+
}
63+
64+
65+
}
66+
67+
/*contributed by: nilesh05apr */

0 commit comments

Comments
 (0)