递归N皇后Java
我自己在解决N皇后的问题,并采用了解决方案中以及在线提到的不同方法
我的代码适用于4以下的输入,但开始为4之后的任何值打印每个案例(即使是错误的案例)。我已经检查了很多次了,但是我在代码中找不到任何错误
PFA检查代码,看看是否能找到错误。 谢谢
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
Scanner scn = new Scanner(System.in);
int n= scn.nextInt();
int[][] arr = new int[n][n];
printNQueens(arr,"",0);
System.out.println();
}
public static void printNQueens(int[][] chess, String qsf, int row) {
if(row==chess.length)
{
qsf = qsf + ".";
System.out.println(qsf);
return;
}
for(int j=0;j<chess[0].length;j++)
{
if(chess[row][j]==0)
{
int x=row,y=j;
while(x<chess.length)
{
chess[x][y] = 1;
x++;
}
x = row;
while(x<chess.length && y>=0)
{
chess[x][y] = 1;
x++;
y--;
}
x = row;
y = j;
while(x<chess.length && y<chess[0].length)
{
chess[x][y] = 1;
x++;
y++;
}
printNQueens(chess,qsf + row + "-" + j + ", ",row+1);
x = row;
y = j;
while(x<chess.length)
{
chess[x][y] = 0;
x++;
}
x = row;
while(x<chess.length && y>=0)
{
chess[x][y] = 0;
x++;
y--;
}
x = row;
y = j;
while(x<chess.length && y<chess[0].length)
{
chess[x][y] = 0;
x++;
y++;
}
}
}
}
}
# 1 楼答案
导入java。util.*
公共类主{
}