Java 在棋盘上放置12名骑士的算法,因此每个方块要么被占领,要么被攻击
我正在努力解决这个问题。我写了一些代码,一个试图找到这个问题的解决方案的递归,但是它需要很多时间来处理。我怎样才能使这种方法更有效Java 在棋盘上放置12名骑士的算法,因此每个方块要么被占领,要么被攻击,java,dynamic,chess,Java,Dynamic,Chess,我正在努力解决这个问题。我写了一些代码,一个试图找到这个问题的解决方案的递归,但是它需要很多时间来处理。我怎样才能使这种方法更有效 public static int placeKnights(Square current, int[][] board, int knightsPlaced) { ArrayList<Square> canAttackThisSquare = Square.canReachThisSquare(current); //Get a lis
public static int placeKnights(Square current, int[][] board, int knightsPlaced) {
ArrayList<Square> canAttackThisSquare = Square.canReachThisSquare(current); //Get a list of squares, that can attack our current square
for (Square square : canAttackThisSquare) { //Take each square from the list
int[][] currBoard = Main.copyMatrix(board); //Copy the board, for next call
Square curr = new Square(current.x, current.y); //Copy the current square, for next call
int knights = knightsPlaced + 1; //Current knights placed (copying, so original knightsPlaced remain the same, to use when backtracking)
ArrayList<Square> canBeAttackedFromSquare = Square.canReachThisSquare(square); //Get a list of squares, that can be attacked by the new knight
for (Square sq : canBeAttackedFromSquare) { //Put 1, to empty squares.
if (currBoard[sq.x][sq.y] != 2) {
currBoard[sq.x][sq.y] = 1;
}
}
// Get next square to attack
while (board[current.x][current.y] != 0) {
if (current.x == 7) {
if (current.y == 7) {
return knights; //If the board is done then finish the recursion
} else {
current.x = 0;
current.y++;
}
} else {
current.x++;
}
}
if (knights == 12) {
return 13; //If the board is not done and we have already placed 12 knights, then end the recursion and return >12 value
}
if (placeKnights(curr, currBoard, knights) == 12) { //Else call the method on the next square, and get the result of recursion
return 12; //If the board got filled with 12 knights, then return 12
}
//Else backtrack and try next way
}
return 13; //If it checks all the possible choices, it returns 13, so we backtrack.
}
}
在为Board and Square编写类之后,我尝试了您的代码,但使用System.currentTimeMillis所花费的时间无法测量。所以我认为这部分代码没有问题。你能展示你的Square.canReachThisSquareSquare和你的Main.copyMatrixint[]]方法吗?有很多方法可以改进这段代码,即使不改变算法本身。只是一个想法:你可以用两个长值来表示你的棋盘:在第一个值中,如果有骑士,每个位都是1;在第二个值中,如果受到攻击,每个位都是1。这不仅使得复制非常便宜,而且可以通过简单的按位or实现骑士的放置。