N皇后问题

来源:互联网 发布:js获取当前触发事件 编辑:程序博客网 时间:2024/05/22 13:48
/* * 名称: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++ ;}}}}

0 0
原创粉丝点击