9.9递归和动态规划(九)——N皇后
2024-10-01 19:02:18
/**
* 功能:打印八皇后在8*8棋盘上的各种摆法。当中每一个皇后都不同行、不同列,也不在对角线上。
* 这里的“对角线”指的是全部的对角线,不仅仅是平分整个棋盘的那两条对角线。
*/
static int GRID_SIZE=8; /**
* 思路:每一行仅仅能摆放一个皇后,因此不须要将棋盘存储为完整的8*8矩阵。仅仅需一维数组,当中columns[r]=c表示有个皇后位于r行c列。
* @param row
* @param columns
* @param results
*/
public static void placeQueen(int row,Integer[] columns,ArrayList<Integer[]> results){
if(row==GRID_SIZE){
/*Creates and returns a copy of this object. The precise meaning of "copy" may depend on the class of the object.
* The general intent is that, for any object x, the expression:
x.clone() != x will be true.
* and that the expression:
x.clone().getClass() == x.getClass() will be true.
* but these are not absolute requirements. While it is typically the case that:
x.clone().equals(x) will be true, this is not an absolute requirement. */
results.add(columns.clone());
}else{
for(int col=0;col<GRID_SIZE;col++){
if(checkValid(columns,row,col)){
columns[row]=col;//摆放皇后
placeQueen(row+1, columns, results);
}
}
}
} /**
* 检查(row,column)能否够摆放皇后。方法:
* 检查有无其它皇后位于同一列或对角线。不必检查是否在同一行上,由于调用placeQueen时,一次仅仅会摆放一个皇后。 由此可知,这一行是空的。
* @param columns
* @param row
* @param column
* @return
*/
public static boolean checkValid(Integer[] columns,int row,int column){
for(int r=0;r<row;r++){
int c=columns[r];
/* 检查同一列是否有皇后 */
if(c==column)
return false; /* 检查对角线:
* 若两行的距离等于两列的距离。则表示两个皇后在同一对角线上。 */
int columnDistance=Math.abs(c-column);
int rowDistance=row-r;//row>r,不用取绝对值
if(columnDistance==rowDistance)
return false;
} return true;
}
最新文章
- CentOS 下运维自动化 Shell 脚本之 expect
- ACM: 限时训练题解-Runtime Error-二分查找
- ASP.Net将图片以二进制方式存入数据库,并读取
- 高通平台点亮LCD个人总结
- lubuntu安装maven
- 百度地图api之如何自定义标注图标
- POJ 1655 Balancing Act&;&;POJ 3107 Godfather(树的重心)
- 【转】linux内核调试技巧之一 dump_stack
- SqlServer日期查询
- tableview 详解I
- Java中调用文件中所有bat脚本
- RabbitMQ Linux(Redhat6.5)安装(二 )
- Ionic3关闭弹出页面,跳转到列表后刷新父页面
- Mesos源码分析(1): Mesos的启动过程总论
- UVA - 558 Wormholes (SPEA算法模板题)
- Java的this关键字在继承时的作用
- POJ1742----Coins
- android layout文件优化
- 面试:C++观察者模式实现
- Android am命令使用