八皇后描述-图解
写法思路 使用回溯和栈或双端队列实现
提示:
1. 存储每一次回溯对应的索引信息
2. 每次都要判断当前层索引与之前回溯层的索引是否有冲突( 判断是否在同一列上, 或同一斜线上)
3. 不管在某一层上循环一次都要更新当前层的索引信息
八皇后规则:
* 思路:
* 同一行上怎么判断: 其实就是判断每一层的索引是否有相同的 有相同就代表有同一行的
* 同一斜线上怎么处理: 如果列差== 行差就是同一斜线上
* 如何判断列差:当前原循环层对应的索引- 当前层准备添加的索引 就是列差
* 如果判断行差:当前原循环层数- 当前原循环最大层数
代码实现
public class EightQueenDemo {
public static void main ( String[ ] args) {
List< List< Integer> > eightQueenGroupWay = EightQueen. getEightQueenGroupWay ( 8 ) ;
System. out. println ( "一共有:" + eightQueenGroupWay. size ( ) + "种方式" ) ;
for ( List< Integer> arr: eightQueenGroupWay) {
System. out. println ( arr. toString ( ) ) ;
}
}
}
class EightQueen {
public static List< List< Integer> > getEightQueenGroupWay ( Integer chessboardSize) {
List< List< Integer> > resultList= new ArrayList < > ( ) ;
Deque< Integer> layerIndexs= new ConcurrentLinkedDeque < > ( ) ;
getEightQueenGroupWay ( chessboardSize, resultList, layerIndexs) ;
return resultList;
}
private static void getEightQueenGroupWay ( Integer chessboardSize, List< List< Integer> > resultList, Deque< Integer> layerIndexs) {
for ( int index= 0 ; index< chessboardSize; index++ ) {
if ( EightQueenRuleJudge ( layerIndexs, index) ) {
layerIndexs. addLast ( index) ;
if ( chessboardSize== layerIndexs. size ( ) ) {
List< Integer> queenGroupList= new ArrayList < > ( ) ;
for ( Integer currIndex: layerIndexs. toArray ( new Integer [ layerIndexs. size ( ) ] ) ) {
queenGroupList. add ( currIndex) ;
}
resultList. add ( queenGroupList) ;
} else {
getEightQueenGroupWay ( chessboardSize, resultList, layerIndexs) ;
}
layerIndexs. removeLast ( ) ;
}
}
}
private static boolean EightQueenRuleJudge ( Deque< Integer> layerIndexs, Integer currentLayerIndex) {
if ( layerIndexs. contains ( currentLayerIndex) ) {
return false ;
}
Object[ ] layerIndexsArr= layerIndexs. toArray ( ) ;
for ( int index= 0 ; index< layerIndexsArr. length; index++ ) {
if ( Math. abs ( index- layerIndexsArr. length) == Math. abs ( ( ( Integer) layerIndexsArr[ index] ) - currentLayerIndex) ) {
return false ;
}
}
return true ;
}
}
结果