【发布时间】:2022-07-21 18:45:03
【问题描述】:
我试图解决这个问题,但没有奏效。 描述: 实现它的静态方法:
-
int[][] spiral(int rows, int columns)
返回以表格形式出现的二维数组,其中包含从1到rows * columns的数字。表格的大小将由给定的参数指定。
数字以螺旋方式从顶层角落顺时针填充“表格”。
例如,对于参数值(3, 4),输出数组应为:1 2 3 4 10 11 12 5 9 8 7 6 static int[][] spiral(int rows, int columns) { int mat[][] = new int[rows][columns]; int counter = 1; int startCol = 0; int endCol = columns - 1; int startRows = 0; int endRows = rows -1; while (startRows <= endRows && startCol <= endCol){ for (int i = startCol; i <= endCol; i++){ mat[startRows][i] = counter; counter++; } startRows++; for (int j = startRows; j <= endRows; j++){ mat[j][endCol] = counter; counter++; } endCol--; for (int l = endCol; l >= startCol; l--){ mat[endRows][l] = counter; counter++; } endRows--; for(int y = endRows; y >= startRows; y--){ mat[y][startCol] = counter; counter++; } startCol++; } return mat; }
}
预期:
[[1;2;3;4;5;6];
[18;19;20;21;22;7];
[17;28;29;30;23;8];
[16;27;26;25;24;9];
[15;14;13;12;11;10]]
实际:
[[1;2;3;4;5;6];
[18;19;20;21;22;7];
[17;28;31;30;23;8];
[16;27;26;25;24;9];
[15;14;13;12;11;10]]
【问题讨论】:
-
您应该使用调试器并单步执行您的代码。看来您的循环执行正确,直到通过中心的最后一行。你可能正确地写了 29 和 30,然后用 31 覆盖 29。