The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return all distinct solutions to the n-queens puzzle.
Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.
For example,
There exist two distinct solutions to the 4-queens puzzle:
[
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
解法简单,贪心算法,从第1行到第n行遍历,每次保证不会被前面的皇后杀到,如果能遍历到最后一行,就代表当前的解法可行。这里需要设置一个n长的标志数组,存放皇后所在的位置,用于检测后面放置的皇后是否会被杀到。从下图可以看到,这种解法的时间复杂度不高。
Java代码:
-
public class Solution{
-
public List<String[]> solveNQueens(int n) {
-
int []flag = new int[n];
-
for(int i = 0; i < n; i ++){
-
flag[i] = -1;
-
}
-
List<String[]> result = new ArrayList<String[]>();
-
for(int i = 0; i < n; i ++){
-
flag[0] = i;
-
queens(n, 1, flag, result);
-
}
-
return result;
-
}
-
public void queens(int n, int curRow, int []flag, List<String[]> result)
-
{
-
if(curRow == n){
-
String []solution = new String[n];
-
for(int i = 0; i < n; i ++){
-
String rowSol = "";
-
for(int j = 0;j < n; j ++){
-
if(flag[i] != j){
-
rowSol += '.';
-
}else{
-
rowSol += 'Q';
-
}
-
}
-
solution[i] = rowSol;
-
}
-
result.add(solution);
-
return;
-
}
-
for(int i = 0; i < n; i ++){
-
int j = 0;
-
for(; j < curRow;j++){
-
if((i == flag[j]) || (i == flag[j] + (curRow - j)) || (i == flag[j] - (curRow - j))){
-
break;
-
}
-
}
-
if(j == curRow){
-
flag[curRow] = i;
-
queens(n, curRow + 1, flag, result);
-
}
-
}
-
}
-
}
阅读(1939) | 评论(0) | 转发(0) |