[英]n Queens Java not working for 4 by 4
我输入的n Queens版本似乎适用于除4x4板以外的所有输入。 它需要一个棋盘大小和一个1个女王的起始位置。 有什么原因不能解决该大小的问题? 我尝试输入4 1 2,但无法正确创建电路板
import java.io.*;
public class nQueens {
public static int N;
public static int skipCol;
public static int permaRow;
public static void printSolution(int board[][]) {
PrintWriter file = null;
try {
file = new PrintWriter("solution.txt");
// Prints Board to solution.txt
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (board[i][j] == 1) {
// If board = 1 then there is a Queen, 0 then empty
file.println((i + 1) + " " + (j + 1));
}
}
}
file.flush();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static boolean isSafe(int board[][], int row, int col) {
// Returns True if safe, returns False if not safe
// Checks all columns in the row
int i,j;
for (i = 0; i < col; i++) {
if (board[row][i] == 1) {
return false;
}
}
// Check Diagonals (upper then lower)
for (i = row, j = col; i >= 0 && j >= 0; i--, j--) {
if (board[i][j] == 1) {
return false;
}
}
for (i = row, j = col; j >= 0 && i < N; i++, j--) {
if (board[i][j] == 1) {
return false;
}
}
return true;
}
public static boolean solveNQueensCol(int board[][], int col) {
if (col >= N) { // Base Case, checks if all queens are placed
return true;
}
if (col != skipCol) {
for (int i = 0; i < N; i++) {
if (isSafe(board, i, col)) {
board[i][col] = 1; // Changes that board space to Queen
if (solveNQueensCol(board, col + 1) == true) {
// Recursively places all the Queens onto the board
return true;
}
// If placing queen at i, col doesn't work, remove it
board[i][col] = 0;
}
}
} else {
board[permaRow][skipCol] = 1; // One Preset Queen
return solveNQueensCol(board,col+1);
}
return false;
}
public static boolean solveNQueens(int x, int y) {
// Creates new board with size N
int board[][] = new int[N][N];
for (int i = 0; i < N; i++) { // Fills board with 0s
for (int j = 0; j < N; j++) {
board[i][j] = 0;
}
}
permaRow = x;
skipCol = y;
if (solveNQueensCol(board, 0) == false) {
PrintWriter file = null;
try {
file = new PrintWriter("solution.txt");
// Prints Board to solution.txt
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (board[i][j] == 1) {
// If board = 1 then there is a Queen, 0 then empty
file.println((i + 1) + " " + (j + 1));
}
}
}
file.flush();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
printSolution(board);
return true;
}
public static void main(String[] args) {
N = Integer.parseInt(args[0]);
solveNQueens(Integer.parseInt(args[1]) - 1, Integer.parseInt(args[2]) - 1);
}
}
如果行和列的计数是从0到3,则当女王在1,2位开始时没有任何解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.