您的位置:首页 > 产品设计 > UI/UE

51. N-Queens && 52. N-Queens II

2016-01-12 20:47 369 查看
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

N皇后问题,不能有两个皇后在同一行、列、斜线。两个题一个要求返回结果,一个要求返回解的个数。

DFS。

List<List<String>> r = new ArrayList<List<String>>();
public List<List<String>> solveNQueens(int n) {
char[][] q = new char

;
for(int i = 0;i < n;i++){
for(int j = 0;j < n;j++){
q[i][j] = '.';
}
}
boolean[] col = new boolean
;   //标记该列有没有被皇后占领
boolean[] d1 = new boolean[2*n];  //标记该斜线有没有被皇后占领
boolean[] d2 = new boolean[2*n];
nQueens(n,q,0,col,d1,d2);
return r;
}
private void nQueens(int n, char[][] q,int row,boolean[] col,boolean[] d1,boolean[] d2){
if (row == n) {                                 //success
List<String> tmp = new ArrayList<String>();
for(char[] c:q){
tmp.add(new String(c));
}
r.add(tmp);
return;
}
for (int j = 0; j < n; j++) {
int td1 = row+j , td2 = j - row+n;
if(col[j] || d1[td1] || d2[td2]) continue;
col[j] = true;
d1[td1] = true;
d2[td2] = true;
q[row][j] = 'Q';
nQueens(n, q, row+1,col,d1,d2);
col[j] = false;
d1[td1] = false;
d2[td2] = false;
q[row][j] = '.';
}
}


int num;
public int totalNQueens(int n) {
boolean[] col = new boolean
;   //标记该列有没有被皇后占领
boolean[] d1 = new boolean[2*n];  //标记该斜线有没有被皇后占领
boolean[] d2 = new boolean[2*n];
nQueens(n,0,col,d1,d2);
return num;
}

private void nQueens(int n,int row,boolean[] col,boolean[] d1,boolean[] d2){
if (row == n) {                                 //success
num++;  //计数
return;
}
for (int j = 0; j < n; j++) {
int td1 = row+j , td2 = j - row+n;
if(col[j] || d1[td1] || d2[td2]) continue;
col[j] = true;
d1[td1] = true;
d2[td2] = true;
nQueens(n, row+1,col,d1,d2);
col[j] = false;
d1[td1] = false;
d2[td2] = false;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: