package quess;
/**
* 由于八个皇后的任意两个不能处在同一行,那么这肯定是每一个皇后占据一行。
* 于是我们可以定义一个数组ColumnIndex[8],数组中第i个数字表示位于第i行的皇后的列号。
* 先把ColumnIndex的八个数字分别用0-7初始化,接下来我们要做的事情就是对数组ColumnIndex做全排列。
* 由于我们是用不同的数字初始化数组中的数字,因此任意两个皇后肯定不同列。
* 我们只需要判断得到的每一个排列对应的八个皇后是不是在同一对角斜线上,
* 也就是数组的两个下标i和j,是不是i-j==ColumnIndex[i]-Column[j]或者j-i==ColumnIndex[i]-ColumnIndex[j]。
*
*/
public class quessTest { public static int count =0; //进行全排列 public static void AllSort(int array[],int length,int index) { int n = array.length; if(length == index) { if(check(array)) { count++; System.out.println("第"+count+"种放法:"); for(int i=0;i<n;i++) { for(int j=1;j<=n;j++) { //array数组中存放的是从1到8的所以上面的第二个循环从1开始,到8结束。 if(j==array[i]) System.out.print(" X "); else { System.out.print(" 0 "); } } System.out.println(); } } } else { for(int j=index;j<length;j++) { int tem = array[j]; array[j] = array[index]; array[index] = tem; AllSort(array,n,index+1); /* tem = array[index]; array[index] = array[j]; array[j] = tem; */ tem = array[j]; array[j] = array[index]; array[index] = tem; } } } public static boolean check(int array[]) { int n = array.length; for(int i=0;i<n;i++) for(int j=i+1;j<n;j++) { if(i-j == array[i] - array[j] || j-i == array[i] - array[j]) return false; } return true; } public static void main(String[] args) { int arr[] = new int[8]; for(int i=0;i<8;i++) { arr[i] = i+1; } AllSort(arr,arr.length,0); } }