我需要在螺旋阵列中添加枢轴点,如下所示:
21 22 23 24 25 20 7 8 9 10 19 6 1 2 11 18 5 4 3 12 17 16 15 14 13
我有 java 代码可以做到这一点,它适用于如上所示的小型 5x5 数组......但是当我用大型 1001x1001 数组测试它时,它给了我很多堆栈溢出。我不知道如何跟踪它,我已经使用 try and catch 没有成功。代码如下。有没有人有什么建议?
public class Spiral {
int[][] arr = new int[1001][1001];
int counter = 1;
public int total = 1;
String direction = "SOUTH";
public Spiral(){
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
arr[i][j] = 0;
}
}
try {
arr[500][500] = 1;
spiral(500, 501);
total += arr[0][arr.length - 1];
System.out.println(total);
} catch (Exception e) {
e.printStackTrace();
//System.out.println(x + ", " + y);
}
}
public void spiral(int x, int y) {
counter++;
arr[x][y] = counter;
if(x==900&&y==900)
System.out.println("here");
if (direction == "SOUTH") {
if (arr[x][y - 1] != 0) {
if (x + 1 < arr.length)
spiral(x + 1, y);
} else {
total += arr[x][y];
direction = "WEST";
spiral(x, y - 1);
}
} else if (direction == "WEST") {
if (arr[x - 1][y] != 0) {
if (y - 1 >= 0) {
spiral(x, y - 1);
}
} else {
total += arr[x][y];
direction = "NORTH";
spiral(x - 1, y);
}
} else if (direction == "NORTH") {
if (arr[x][y + 1] != 0) {
if (x - 1 >= 0) {
spiral(x - 1, y);
}
} else {
total += arr[x][y];
direction = "EAST";
spiral(x, y + 1);
}
} else if (direction == "EAST") {
if (arr[x + 1][y] != 0) {
if (y + 1 < arr.length) {
spiral(x, y + 1);
}
} else {
total += arr[x][y - 1];
direction = "SOUTH";
spiral(x + 1, y);
}
}
}
}