给定尺寸为8x8的2D阵列。用户输入随机起始位置和随机结束位置。在Java中,程序必须生成序列号(从0开始,用于起始位置)直到结束位置。首先,从起始位置左侧或右侧向上的节点将变为1.然后,如果它们为空,则从1的左侧或右侧向上的节点将变为2。
我尝试过嵌套循环来生成数字,但是无法覆盖整个矩阵。我认为递归在这里工作得很好,但我并不精通编写递归问题。我已经考虑过首先将整个矩阵初始化为0,然后在S处有用户输入起始位置,在E处结束位置。然后在while循环中,数字将生成,直到end(E)成为另一个char / number。
在这种情况下,我没有将End(E)更改为数字或将Start(S)更改为数字,因此更容易可视化。
4 3 2 3 4 5 0 0
3 2 1 2 3 4 5 0
2 1 S 1 2 3 4 5
3 2 1 2 3 4 5 0
4 3 2 3 4 5 0 0
5 4 3 4 5 E 0 0
0 5 4 5 0 0 0 0
0 0 5 0 0 0 0 0
它可以用嵌套循环完成。
诀窍是要认识到你正在建造连续数字的同心钻石,例如:第三步是:
3 yDelta = -3 xDelta = 0
3 3 yDelta = -2 xDelta = ±1
3 3 yDelta = -1 xDelta = ±2
3 S 3 yDelta = 0 xDelta = ±3
3 3 yDelta = 1 xDelta = ±2
3 3 yDelta = 2 xDelta = ±1
3 yDelta = 3 xDelta = 0
这可以用一个循环完成,计算从yDelta
到-3
的+3
,
并计算xDelta = ±(3 - abs(yDelta))
码
private static void printDistances(int width, int height, int xStart, int yStart, int xEnd, int yEnd) {
// Build clear board
String[][] board = new String[height][width];
for (int i = 0; i < height; i++)
Arrays.fill(board[i], ".");
// Mark start and end locations
board[yStart][xStart] = "S";
board[yEnd][xEnd] = "E";
// Add distances (steps) from start location until end location reached
int endStep = Math.abs(xEnd - xStart) + Math.abs(yEnd - yStart);
for (int step = 1; step < endStep; step++) {
String stepValue = String.valueOf(step);
for (int dy = -step; dy <= step; dy++) {
int y = yStart + dy;
if (y >= 0 && y < height) {
int dx = step - Math.abs(dy);
if (xStart - dx >= 0 && xStart - dx < width)
board[y][xStart - dx] = stepValue;
if (dx != 0 && xStart + dx >= 0 && xStart + dx < width)
board[y][xStart + dx] = stepValue;
}
}
}
// Print the board
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
if (x != 0)
System.out.print(" ");
System.out.printf("%2s", board[y][x]);
}
System.out.println();
}
}
例1
printDistances(8, 8, 2, 2, 5, 5);
4 3 2 3 4 5 . .
3 2 1 2 3 4 5 .
2 1 S 1 2 3 4 5
3 2 1 2 3 4 5 .
4 3 2 3 4 5 . .
5 4 3 4 5 E . .
. 5 4 5 . . . .
. . 5 . . . . .
例2
printDistances(20, 10, 19, 6, 2, 3);
. . . . . . 19 18 17 16 15 14 13 12 11 10 9 8 7 6
. . . . . 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5
. . . . 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4
. . E 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3
. . 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2
. 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 S
. 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
. . 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2
. . . 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3