下面是我尝试打印 8 个皇后问题的所有解决方案(将 8 个皇后放在棋盘上,这样它们都不会互相攻击)。但是,此解决方案仅打印 4 个答案,而 92 应该存在。任何人都看到有什么问题吗?
static int[][] visited = new int[8][8];
static int[][] board = new int[8][8];
static int numQueens = 0;
public static void main(String[] args) {
//call recursive method from every starting position
for(int i=0; i<8; i++){
for(int j=0; j<8; j++){
putQueens(board, i, j);
//clear board and visited array, as well as numQueens
for(int i2=0; i2<8; i2++){
for(int j2=0; j2<8; j2++){
board[i2][j2]=0;
visited[i2][j2]=0;
}
}
numQueens=0;
}
}
}
static void putQueens(int[][]board, int row, int col){
if(visited[row][col]==1)
return;
visited[row][col]=1;
boolean hasQueen = false;
//check columns
for(int j=0; j<board[0].length; j++){
if(board[row][j]==1)
hasQueen = true;
}
//check rows
for(int i=0; i<board.length; i++){
if(board[i][col]==1)
hasQueen = true;
}
//check diagonals
for(int i=row; i<board.length; i++){
if(col+(i-row)<=7){
if(board[i][col+(i-row)]==1)
hasQueen=true;
}
}
//check diagonals
for(int i=row; i>=0; i--){
if(col-(row-i)>=0){
if(board[i][col-(row-i)]==1)
hasQueen=true;
}
}
//check diagonals
for(int i=row; i<board.length; i++){
if(col-(i-row)>=0){
if(board[i][col-(i-row)]==1)
hasQueen=true;
}
}
//check diagonals
for(int i=row; i>=0; i--){
if(col+(row-i)<=7){
if(board[i][col+(row-i)]==1)
hasQueen=true;
}
}
//print if solution
if(!hasQueen){
board[row][col] = 1;
numQueens++;
if(numQueens==8){
System.out.println("==========");
for(int i=0; i<8; i++){
for(int j=0; j<8; j++){
System.out.print(String.format("%3s", board[i][j]));
board[i][j]=0;
}
System.out.println("");
}
numQueens=0;
}
}
//recurse
if(row!=7)
putQueens(board, row+1, col);
if(col!=7)
putQueens(board, row, col+1);
if(row!=0)
putQueens(board, row-1, col);
if(col!=0)
putQueens(board, row, col-1);
}