我正在尝试解决著名的n皇后问题。而且,我正在尝试记录NxN尺寸板子的所有可能解决方案。
要这样做,请使用ArrayList存储找到的每个主板解决方案。我可以检查代码是否找到解决方案并将其存储在数组列表中。但是,在检查最终数组列表时,它仅包含初始化时的char矩阵。
有人可以帮我看看,到底什么Java不能正确存储char矩阵吗?
谢谢!下面的代码:
public static ArrayList<char[][]> nQueens(int n)
{
char board[][] = new char[n][n];
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
board[i][j] = '-';
ArrayList<char[][]> solution = new ArrayList<char[][]>();
nQueensHelper(board, 0, n, solution);
return solution;
}
public static void nQueensHelper(char [][] board, int row, int N, ArrayList<char[][]> solution)
{
printBoard(board, N);
System.out.println();
if(row == N)
{
System.out.println("solution");
printBoard(board, N);
System.out.println("**\n");
solution.add(board);
return;
}
for(int col = 0; col < N; col++)
{
if(checker(board, row, col, N))
{
board[row][col] = 'q';
nQueensHelper(board, row+1, N, solution);
board[row][col] = '-';
}
}
}
public static boolean checker(char [][] board, int row, int col, int N)
{
//check diagonal - upper-left to bottom-right
for(int i = row, j = col; i >= 0 && j >= 0; i--,j--)
if(board[i][j] == 'q')
return false;
//check column
for(int i = row; i >= 0; i--)
if(board[i][col] == 'q')
return false;
//check diagonal - upper-right to bottom-left
for(int i = row, j = col; i >= 0 && j < N; i--,j++)
if(board[i][j] == 'q')
return false;
return true;
}
public static void printBoard(char board[][], int n)
{
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++)
{
System.out.print(board[i][j]);
}
System.out.println();
}
}
//主要测试
public static void main(String [] args) throws FileNotFoundException, IOException, ParseException, ScriptException
{
ArrayList<char[][]> solution = nQueens(4);
System.out.println(solution);
}