今天从早上开始就在弄回溯法,都说回溯的经典问题是八皇后问题,于是就好好看了一下八皇后的问题。找出所有的情况可能有点难,但是找出一条路来感觉应该挺简单的。
我一直都不怎么会用递归,这个程序依然没有递归。
- /*这个算法主要解决八皇后问题*/
- public class Huisu02 {
- //判断当前点是否处于以前点的对角线上
- public static boolean isdianogal(int x,int y,int[] points){//把当前点的位置传过去 这里y有两个作用:表示当前点的坐标,表示points中点的个数
- //判断正对角线 \
- int xx=0,yy=0;
- xx=x>y?x-y: 0;
- yy=x>y? 0 :y-x;
- for (int i = yy; i < y; i++) {//这里必须从yy开始 因为需要判断x<y的情况
- if(points[i]==xx){
- return true;
- }
- xx++;yy++;
- }
- //判断反对角线 /
- xx=x+y<=7?x+y:7;
- yy=x+y<=7?0:x+y-7;
- for (int i = yy; i < y; i++) {//这里必须从yy开始 因为需要判断x<y的情况
- if(points[i]==xx){
- return true;
- }
- xx--;yy++;
- }
- return false;
- }
- public static void huisu(){
- }
- public static void main(String[] args) {
- int[] samerow = new int[8];// 判断是否同列
- int[] points=new int[8];//存储点的x轴的坐标
- int index=0;
- boolean backed=false;
- points[index++]=0;
- samerow[0]=1;
- while (index<8) {
- int i=0;
- if(!backed){
- for (i = 0; i < points.length; i++) {
- if(samerow[i]==0){//这一列是可选的
- if(!isdianogal(i, index, points)){//不在对角线内
- points[index++]=i;
- samerow[i]=1;
- break;
- }
- }
- }
- }else {
- for (i = points[index]+1; i < points.length; i++) {
- if(samerow[i]==0){//这一列是可选的
- if(!isdianogal(i, index, points)){//不在对角线内
- points[index++]=i;
- backed=false;
- samerow[i]=1;
- break;
- }
- }
- }
- }
- if(i>=8){//这一行已经没有可以选择的了 退回到上一行去
- index--;
- samerow[points[index]]=0;
- backed=true;
- }
- }
- //把得到的结果反映到棋盘上面去
- int[][] cheesbord = new int[8][8];// 代表棋盘放置了皇后就为1,没放就是0
- int j=0;
- for (int i = 0; i < points.length; i++) {
- cheesbord[i][points[j]]=1;
- j++;
- }
- for (int i = 0; i < 8; i++) {
- for (j = 0; j < 8; j++) {
- if(cheesbord[i][j]==1){
- System.err.print(cheesbord[i][j]+" ");
- }
- System.err.print("# ");
- }
- System.err.println();
- }
- }
- }
对于八皇后问题的描述在ppt里面。
转载于:https://blog.51cto.com/sbp810050504/701540