八皇后

 1 public class EightQueenDemo {
 2     
 3     public static int count = 0;
 4     public boolean check(int array[][], int num, int i, int j) {
 5         for(int k = 0; k < num; k++) {
 6             if(array[i][k] == 1)
 7                 return false;
 8             if(array[k][j] == 1)
 9                 return false;
10         }
11         for(int s = i - 1, t = j - 1; s >= 0 && t >= 0; s--, t--) {
12             if(array[s][t] == 1)
13                 return false;
14         }
15         for(int s = i - 1, t = j + 1; s >= 0 && t < num; s--, t++) {
16             if(array[s][t] == 1)
17                 return false;
18         }
19         return true;
20     }
21     
22     private void printQueen(int[][] array, int num) {
23         System.out.println(num + "皇后的一种解法:");
24         for(int i = 0; i < num; i++) {
25             for(int j = 0; j < num; j++) {
26                 System.out.print(array[i][j] + " ");
27             }
28             System.out.println();
29         }
30     }
31     
32     public void find(int[][] array, int num, int row) {
33         if(row > 7) {
34             count++;
35             printQueen(array, num);
36             return;
37         }
38         for(int col = 0; col < num; col++) {
39             if(check(array, num, row, col)) {
40                 array[row][col] = 1;
41                 find(array, num, row + 1);
42                 array[row][col] = 0;//一种解法找完后,将本位置重新置为0
43             }
44         }
45     }
46     
47     public static void main(String[] args) {
48         int num = 8;
49         int[][] array = new int[num][num];
50         EightQueenDemo eqd = new EightQueenDemo();
51         eqd.find(array, num, 0);
52         System.out.println("八皇后一共有:" + count + "种解法");
53     }
54 }
原文地址:https://www.cnblogs.com/heyboom/p/10220799.html