回溯算法之八皇后问题的解--java实现

最近在学习数据结构与算法这块,参考别人的代码,自己写了一遍回溯算法的八皇后实现,记录一下,以备自己复习。

不多说了,直接上代码。

public class Backtrack8Queens {

    private static int[][] result = new int[8][8];
    public static void main(String[] args) {
        System.out.println("hello,world!");
        calc8queens(0);
    }

    public static void calc8queens(int row) {
        if(row == 8) {
            print8queens(result);
            return;
        }

        for(int col = 0; col < 8; ++col) {
            if(check(row, col)) {
                result[row][col] = 1;
                calc8queens(row + 1);
                result[row][col] = 0;
            }
        }
    }

    public static boolean check(int row, int col) {
        int leftup = col - 1;
        int rightup = col + 1;
        for(int i = row - 1; i >= 0; --i) {
            if(result[i][col] == 1) return false;
            if(leftup >= 0 && result[i][leftup] == 1) return false;
            if(rightup < 8 && result[i][rightup] == 1) return false;
            --leftup;
            ++rightup;
        }
        return true;
    }

    public static void print8queens(int[][] result) {
        for(int i = 0; i < result.length; ++i) {
            for(int j = 0; j < result[0].length; ++j) {
                System.out.print(String.format("%s\t", result[i][j]));
            }
            System.out.println();
        }
        System.out.println();
    }
}

运行结果如下:

hello,world!
1	0	0	0	0	0	0	0	
0	0	0	0	1	0	0	0	
0	0	0	0	0	0	0	1	
0	0	0	0	0	1	0	0	
0	0	1	0	0	0	0	0	
0	0	0	0	0	0	1	0	
0	1	0	0	0	0	0	0	
0	0	0	1	0	0	0	0	

1	0	0	0	0	0	0	0	
0	0	0	0	0	1	0	0	
0	0	0	0	0	0	0	1	
0	0	1	0	0	0	0	0	
0	0	0	0	0	0	1	0	
0	0	0	1	0	0	0	0	
0	1	0	0	0	0	0	0	
0	0	0	0	1	0	0	0	

1	0	0	0	0	0	0	0	
0	0	0	0	0	0	1	0	
0	0	0	1	0	0	0	0	
0	0	0	0	0	1	0	0	
0	0	0	0	0	0	0	1	
0	1	0	0	0	0	0	0	
0	0	0	0	1	0	0	0	
0	0	1	0	0	0	0	0	

1	0	0	0	0	0	0	0	
0	0	0	0	0	0	1	0	
0	0	0	0	1	0	0	0	
0	0	0	0	0	0	0	1	
0	1	0	0	0	0	0	0	
0	0	0	1	0	0	0	0	
0	0	0	0	0	1	0	0	
0	0	1	0	0	0	0	0	

0	1	0	0	0	0	0	0	
0	0	0	1	0	0	0	0	
0	0	0	0	0	1	0	0	
0	0	0	0	0	0	0	1	
0	0	1	0	0	0	0	0	
1	0	0	0	0	0	0	0	
0	0	0	0	0	0	1	0	
0	0	0	0	1	0	0	0	

0	1	0	0	0	0	0	0	
0	0	0	0	1	0	0	0	
0	0	0	0	0	0	1	0	
1	0	0	0	0	0	0	0	
0	0	1	0	0	0	0	0	
0	0	0	0	0	0	0	1	
0	0	0	0	0	1	0	0	
0	0	0	1	0	0	0	0	

0	1	0	0	0	0	0	0	
0	0	0	0	1	0	0	0	
0	0	0	0	0	0	1	0	
0	0	0	1	0	0	0	0	
1	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	1	
0	0	0	0	0	1	0	0	
0	0	1	0	0	0	0	0

...

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值