我必须编写代码来设置一个 8x8 矩阵、一个棋盘,然后询问用户想要将皇后放置在哪一行和哪一列。然后我必须在皇后可以移动到的每个方格上打上*。在皇后可以移动到的行和列上加上 * 并不困难,但我在正确标记皇后可以移动的对角线时遇到了困难。这是我迄今为止编写的尝试定位对角线的代码:
char[][] chessboard = new char[8][8];
System.out.print("What row do you want to place the queen on? ");
int row = console.nextInt();
System.out.print("What column do you want to place the queen on? ");
int column = console.nextInt();
char queen = 'Q';
chessboard[row - 1][column - 1] = queen;
// column and rows
for (int i = 0; i < chessboard.length; i++) {
for (int j = 0; j < chessboard[0].length; j++) {
if ((i == 2 || j == 6) && chessboard[i][j] != queen) {
chessboard[i][j] = '*';
}
}
}
if ((row - 1) != 0) {
// left diagonal
for (int i = 0; i < row; i++) {
for (int j = (column - 1 - (row - 1)); ((column - 1) - (row - 1)) <= j && j < column; j++) {
if (chessboard[i][j] != queen) {
chessboard[i][j] = '*';
}
}
}
for (int i = (row - 1) + (8 - (column)); i >= row - 1; i--) {
for (int j = 7; j >= (column - 1); j--) {
if (chessboard[i][j] != queen) {
chessboard[i][j] = '*';
}
}
}
// right diagonal
for (int i = 7; i >= row - 1; i--) {
for (int j = (column - 1 - (row - 1)); 0 <= j && j < column; j--) {
if (chessboard[i][j] != queen) {
chessboard[i][j] = '*';
}
}
}
}
for (int i = 0; i < chessboard.length; i++) {
for (int j = 0; j < chessboard[0].length; j++) {
System.out.print(chessboard[i][j] + " ");
}
System.out.println();
}
}
当我输入实验值(例如第 3 行和第 7 列)时,我得到的输出非常困惑。对于上面的数字,我得到:
[][][][] * * * []
[][][][] * * * []
* * * * * * Q *
* * * * * [] * *
* * * * * [] * []
* * * * * [] * []
* * * * * [] * []
* * * * * [] * []
有人可以告诉我哪里出错了吗? * 这是一个家庭作业问题,因此请仅在答案中编码。谢谢!
最佳答案
如果是我,我会简单地遍历棋盘的每个方格,并测试每个方格作为皇后可以移动到的三个可能规则中的有效性,即
square.x == queen.x ||
square.y == queen.y ||
|square.x - queen.x| == |square.y - queen.y|
如果您的方格符合上述任何规则,那么它就是一个可以移动到的有效方格,否则就不是。当然,忽略女王当前居住的广场
square.x != queen.x && square.y != queen.y
伪代码:
for (int i = 0; i < chessboard.length; i++) {
for (int j = 0; j < chessboard[0].length; j++) {
// You could encapsulate these lines in a isValidSquareForQueenMove(x, y) method.
boolean isSquareValid = false;
isSquareValid = isSquareValid || x == queen.x;
isSquareValid = isSquareValid || y == queen.y;
isSquareValid = isSquareValid || Math.abs(queen.x - x) == Math.abs(queen.y - y);
isSquareValid = isSquareValid && x != queen.x && y != queen.y;
// Do stuff here.
}
}
关于java - 查找二维方形数组中任意随机点的对角线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36015169/