/*
* 名称:N皇后问题
* 题目:将N个皇后放置在N×N的国际象棋棋盘上,其中没有任何两个皇后处于同一行,同一列或同一对角线上。
*
* 解析思路:
* 遍历所有的可行性,利用回溯法。
* 从第0列开始,遍历所有的可能性,直到行不通或者走到底。
* 但是,得出来的结果比书上说的要多,验证后是正确的。感觉好坑爹。
* */
public static void Queen(){
int length = 4 ;
QueenCell cellArray[] = new QueenCell[length] ;
for(int i = 0 ; i < length ; i++){
cellArray[i] = new QueenCell(-1,i) ;
}
searchDeep(0,length,cellArray) ;
System.out.println(anNum);
}
public static boolean isCanSet(int row,int col,QueenCell[] cellArray)
{
for(int i = 0 ; i < col ; i++){
if(cellArray[i].getRow() == row){
return false ;
}
}
int index = col - 1 ;
if(index < 0){return true ;}
if(row == cellArray[index].getRow() - 1
|| row == cellArray[index].getRow() + 1){
return false ;
}
return true ;
}
public static void searchDeep(int col,int loopTimes,QueenCell[] cellArray){
for(int i = 0 ; i < loopTimes ; i++)
{
if(col > loopTimes){return ;}
if(isCanSet(i,col,cellArray)){
if(col + 1 < loopTimes){
cellArray[col].setRow(i);
searchDeep(col + 1,loopTimes,cellArray) ;
}
else if(col + 1 == loopTimes){
cellArray[col].setRow(i);
for(int j = 0 ; j < cellArray.length ; j++){
System.out.print("(" + cellArray[j].getCol() + "," + cellArray[j].getRow() + "),");
}
System.out.println();
anNum++ ;
}
}
}
}
N皇后问题
最新推荐文章于 2023-08-19 03:28:35 发布