八皇后问题最原始方法优化

package dfs;

import java.util.*;

public class 八皇后3 {
    static int ans[][] = new int[6][6];
    static int lie[] = new int[6];
    static int hang[] = new int[6];
    static int c[] = new int[20];
    static int d[] = new int[20];
    static int ans2 = 0,count = 0;
    public static void main(String[] args) {
        dfs(0,0);
        System.out.println(count);
    }
    static void dfs(int x,int y){
        count++;
        if (y > 5) {
            y = 0;
            x++;
        }
        if (x == 6 || ans2 != x) {//这里加上这句ans2 != x可以少递归十倍
            if (ans2 == 6) {
                for (int i = 0; i < 6; i++) {
                    for (int j = 0; j < 6; j++) {
                        System.out.print(ans[i][j] + " ");
                    }
                    System.out.println();
                }
                System.out.println("**************");
            }
            return;
        }

        //不放皇后
        dfs(x,y + 1);

        //放皇后
        if(lie[x] == 0 && hang[y] == 0 && c[x + y] == 0 && d[y -x + 6] == 0){
            lie[x] = 1;
            hang[y] = 1;
            c[x + y] = 1;
            d[y - x + 6] = 1;
            ans[x][y] = 6;
            ans2++;
            dfs(x + 1,0);
            lie[x] = 0;
            hang[y] = 0;
            c[x + y] = 0;
            d[y - x + 6] = 0;
            ans[x][y] = 0;
            ans2--;
        }



    }
}

这里我直接测试棋盘大小为6时的数据

主要是每次除了最后一行数据不符合要求时,其他的都不会回溯,会接着去递归下面的数据,但是当这一行没有符合要求的空位时,按理来说是不可能为正确答案了,此时就可以回溯了,一旦程序接着往下一行走,就会导致ans2与x不相等,此刻就结束此轮递归,直接return

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值