==========================努力奋斗财源广进==========================
N 皇后问题是指在 n * n 的棋盘上要摆 n 个皇后, 要求:任何两个皇后不同行,不同列也不在同一条斜线上, 求给一个整数 n ,返回 n 皇后的摆法数。
import java.util.*;
public class Solution {
/**
*
* @param n int整型 the n
* @return int整型
*/
Set<Integer> column = new HashSet<Integer>(); //标记列不可用
Set<Integer> posSlant = new HashSet<Integer>();//标记正斜线不可用
Set<Integer> conSlant = new HashSet<Integer>();//标记反斜线不可用
int result = 0;
public int Nqueen (int n) {
// write code here
compute(0, n);
return result;
}
private void compute(int i, int n) {
if (i == n) {
result++;
return;
}
for (int j = 0; j < n; j++) {
if (column.contains(j) || posSlant.contains(i - j) ||
conSlant.contains(i + j)) {
continue;
}
column.add(j);//列号j
posSlant.add(i - j);//行号i - 列号j 正斜线
conSlant.add(i + j);//行号i + 列号j 反斜线
compute(i + 1, n); //计算下一行
column.remove(j); //完成上一步递归计算后,清除
posSlant.remove(i - j);
conSlant.remove(i + j);
}
}
}
//待定
评论区记录复习记录
评论