八皇后问题
八皇后问题是一个以国际象棋为背景的问题:在 8×8 的国际象棋棋盘上放置八个皇后,使得任何一个皇后都无法直接吃掉其他的皇后。为了达到此目的,任两个皇后都不能处于同一条横行、纵行或斜线上。八皇后问题可以推广为更一般的n皇后摆放问题:这时棋盘的大小变为n×n,而皇后个数也变成n。当且仅当 n = 1 或 n ≥ 4 时问题有解。
1 package eight; 2 3 public class huanghou { 4 private int n; 5 private int[] columns; 6 private static int num=0; 7 public huanghou(int n){ 8 this.n=n; 9 this.columns=new int[n]; 10 } 11 public boolean checkPisition(int x){ 12 for(int i=0;i<x;i++){ 13 if(Math.abs(x-i)==Math.abs(columns[x]-columns[i])||columns[x]==columns[i]){ 14 return false; 15 } 16 } 17 return true; 18 } 19 public void recursion(int x){ 20 if(x>n-1){ 21 num++; 22 print(columns); 23 } 24 else{ 25 for(int i=0;i<n;i++){ 26 columns[x]=i; 27 if(checkPisition(x)){ 28 recursion(x+1); 29 } 30 } 31 } 32 } 33 public void print(int[] columns){ 34 int row,col; 35 System.out.println("皇后排布方式:"+num); 36 for(int e:columns){ 37 System.out.print(e+1); 38 } 39 System.out.println("\n皇后位置如图:"); 40 for(row=0;row<n;row++){ 41 for(col=0;col<n;col++){ 42 if(col==columns[row]){ 43 System.out.print("Q"); 44 } 45 else{ 46 System.out.print("*"); 47 } 48 } 49 System.out.println(); 50 } 51 System.out.println(); 52 } 53 public static void main(String[] args){ 54 huanghou eq=new huanghou(8); 55 eq.recursion(0); 56 } 57 58 }
经过程序运行一共有92种皇后的摆置方式。

浙公网安备 33010602011771号