递归解决问题——八皇后
这是一个比较经典的算法问题了,也是用到了递归思路,采用了递归回溯法
public class Queue8 { int max = 8; int[] array = new int[max]; static int count = 0; static int judgeCount = 0; public static void main(String[] args) { Queue8 queue8 = new Queue8(); queue8.check(0); System.out.printf("一共有%d解法\n", count); System.out.printf("一共检测%d次", judgeCount); } //放置皇后 private void check(int n) { if (n == max) { print(); return; } for (int i = 0; i < max; i++) { array[n] = i; if (judge(n)) { check(n + 1); } } } //检查是否冲突 private boolean judge(int n) { judgeCount++; for (int i = 0; i < n; i++) { if (array[i] == array[n] || Math.abs(n - i) == Math.abs(array[n] - array[i])) { return false; } } return true; } //用于输出 private void print() { count++; for (int i = 0; i < array.length; i++) { System.out.print(array[i] + " "); } System.out.println(); } }
相关推荐
steeven 2020-11-10
Tips 2020-10-14
nongfusanquan0 2020-08-18
yedaoxiaodi 2020-07-26
清溪算法君老号 2020-06-27
pengkingli 2020-06-25
yishujixiaoxiao 2020-06-25
清溪算法 2020-06-21
RememberMePlease 2020-06-17
nurvnurv 2020-06-05
SystemArchitect 2020-06-02
码墨 2020-05-29
清溪算法 2020-05-27
choupiaoyi 2020-05-27
清溪算法 2020-05-25
bluewelkin 2020-05-19
dbhllnr 2020-05-15
steeven 2020-05-09
baike 2020-05-09