我正在尝试制作一个骑士游览程序,但是当我尝试从2d数组中的行/列中减去该板时,我就会在棋盘上移动。但我尝试做的每件事都不断尝试将电路板设置为-1而不是减去1.
有点难以解释问题是什么,但是如果有人可以帮助我在这里,我将非常感谢我的代码:
public class Knight1 {
public static void main(String[] args) {
int board[][] = new int[8][8];
int horizontal[] = new int[8];
int vertical[] = new int[8];
horizontal[0] = 2;
horizontal[1] = 1;
horizontal[2] = -1;
horizontal[3] = -2;
horizontal[4] = -2;
horizontal[5] = -1;
horizontal[6] = 1;
horizontal[7] = 2;
vertical[0] = -1;
vertical[1] = -2;
vertical[2] = -2;
vertical[3] = -1;
vertical[4] = 1;
vertical[5] = 2;
vertical[6] = 2;
vertical[7] = 1;
int move = 1;
int moveNumber = 0;
int currentRow = 0;
int currentCol = 0;
int counter = 1;
while (moveNumber != 7) {
currentRow += vertical[moveNumber];
currentCol += horizontal[moveNumber];
board[currentRow][currentCol] = counter;
moveNumber++;
counter++;
}
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
}
}
答案 0 :(得分:0)
问题出现在这一点上:
int currentRow = 0;
int currentCol = 0;
您正尝试将 -1 添加到 currentRow 变量
vertical[0] = -1;
currentRow += vertical[moveNumber];
我只看看Knight的巡演问题和你的代码。如果我正确地理解了它们,你应该从 ROW 7 和 COLUMN 4 开始。
所以只改变这两个变量:
int currentRow = 7;
int currentCol = 4;
它将编译此结果:
0 0 0 0 0 0 0 0
0 0 0 0 4 0 0 0
0 0 5 0 0 0 3 0
0 0 0 0 0 0 0 0
0 6 0 0 0 0 0 2
0 0 0 0 0 0 0 0
0 0 7 0 0 0 1 0
0 0 0 0 0 0 0 0
我还稍微编辑了你的主要方法: 您不需要水平和垂直数组。你可以使用多维数组来完成它。
public static void main(String[] args) {
int board[][] = new int[8][8];
int moveNumber = 0;
int currentRow = 7;
int currentCol = 4;
int counter = 1;
//moves[moveNumber][0] = columnValues;
//moves[moveNumber][1] = rowValues;
int moves[][] = new int[][]{{ 2,-1},
{ 1,-2},
{-1,-2},
{-2,-1},
{-2, 1},
{-1, 2},
{ 1, 2},
{ 2, 1}};
while (moveNumber != 7) {
currentCol += moves[moveNumber][0];
currentRow += moves[moveNumber][1];
board[currentRow][currentCol] = counter;
moveNumber++;
counter++;
}
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++)
System.out.print(board[i][j] + " ");
System.out.println();
}
}