我正在努力解决这个问题。我写了一些代码,一个试图找到这个问题的解决方案的递归,但它需要花费大量的时间来处理。我怎样才能使该方法更有效?
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.
}
}