N皇后问题,也是用递归的方式来解,不一样的是,要加一个record记录之前的皇后的位置来确定之后的皇后放的位置对不对
import java.util.ConcurrentModificationException;
public class NQueens {
public static void main(String[] args) {
NQueens nQueens = new NQueens();
System.out.println(nQueens.num(10));
}
public static int num(int n){
if (n<=0){
return 0;
}
int[] record=new int[n];
return process(0,record,n);
}
//潜台词record[0...i-1]的所有皇后不共行,不共列
//目前来到了第i行
//n代表整体一共有多少行
//返回值是摆完所有的皇后,合理的摆法有多少种
public static int process(int i,int[] record,int n){
if (i==n){//到达了中止行
return 1;
}
int res=0;
for (int j=0;j<n;j++){//当前行在i行,尝试i行的每一列
if(isValid(record,i,j)){
record[i]=j;
res+=process(i+1,record,n);
}
}
return res;
}
private static boolean isValid(int[] record, int i, int j) {
for (int k=0;k<i;k++){
if (j==record[k]||Math.abs(k-i)==Math.abs(record[k]-j)){
return false;
}
}
return true;
}
}
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有