题目描述
一个8*8的棋盘上有八个皇后,使她们互相不能攻击(即两个皇后不能出现在同一行,同一列,或同一对角线上)。
package TraceBack;
public class 八皇后问题 {
public static void main(String[] args) {
// TODO 自动生成的方法存根
int []data={0,1,2,3,4,5,6,7};//用一个数组存放0-7则行列必然不会相等,只考虑对角情况即可;
int []count=new int[1];//用来存放满足情况的个数 92.
八皇后问题 test=new 八皇后问题();
test.permutation(data, 0,count);
System.out.println(count[0]+"");
}
public void permutation(int[] data,int index,int[] count)
{
if(index==data.length-1)
{
boolean flag=true;
for(int i=0;i<8;i++)
{
for(int j=i+1;j<8;j++)
{
if(Math.abs(data[i]-data[j])==Math.abs(i-j))
{
flag=false;
break;
}
}
}
if(flag==true)
{
count[0]++;
}
}
for(int i=index;i<data.length;i++)
{
swap(data,index,i);
permutation(data,index+1,count);
swap(data,index,i);
}
}
public void swap(int []data,int index,int i)
{
int temp=data[index];
data[index]=data[i];
data[i]=temp;
}
}
n-queens
题目描述
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return all distinct solutions to the n-queens puzzle.
Each solution contains a distinct board configuration of the n-queens' placement, where'Q'and'.'both indicate a queen and an empty space respectively.
For example,
There exist two distinct solutions to the 4-queens puzzle:
[ [".Q..", // Solution 1 "...Q", "Q...", "..Q."], ["..Q.", // Solution 2 "Q...", "...Q", ".Q.."] ]
将皇后的位置作为字符数组存储下来,代码如下:
import java.util.*;
public class Solution {
public ArrayList<String[]> solveNQueens(int n) {
ArrayList<String[]> array=new ArrayList();
if(n < 1)
return array;
int[] num=new int[n];//仍用数字数组模拟的方法
for(int i=0;i<n;i++)
num[i]=i;
perm(num,0,array);
return array;
}
public void perm(int[] num,int start,ArrayList<String[]> array)
{
if(start == num.length-1)
{
boolean flag=false;
for(int i=0;i<num.length-1;i++)
{
for(int j=i+1;j<num.length;j++)
{
if(Math.abs(num[i]-num[j]) == Math.abs(i-j))//判断是否不能互相攻击
{
flag=true;
break;
}
}
}
if(flag == false)//若满足要求,则构建字符串数字,并保存下来
{
String[] strs=new String[num.length];
for(int i=0;i<num.length;i++)
{
StringBuilder sb=new StringBuilder();
for(int j=0;j<num.length;j++)
sb.append('.');
sb.setCharAt(num[i],'Q');
strs[i]=sb.toString();
}
array.add(strs);
return;
}
}
for(int i=start;i<num.length;i++)
{
swap(num,start,i);
perm(num,start+1,array);
swap(num,start,i);
}
}
public void swap(int[] num,int i,int j)
{
int temp=num[i];
num[i]=num[j];
num[j]=temp;
}
}