编写一个类,给定一个正整数 N,创建并返回一个由整数组成的方阵 NxN,以螺旋形式显示从 1 到 n^2 的数字
在我的课上我有四个方法,其中三个是方向,而spiral()
方法应该把每个数字放在正确的位置
public static int[][] spiral(int n) {
int[][] res;
int i,j;
int num;
int direction;
/** variables initializzazion */
res=new int[n][n];
i=0;
j=0;
res[i][j]=1;
direction=0;
for(num=2; num<=n*n; num++) {
direction = updateDirection(direction, i, j, n);
if ((direction==1) || (direction==3))
i=updateRow(i, direction);
else
j=updateColoumn(j, direction);
res[i][j]=num;
}
return res;
}
可悲的是,当我尝试运行它时,我得到一个ArrayIndexOutOfBoundException
似乎是由res[i][j]=1;
.
如何修复它以使数组仍然从 1 开始并上升到 N*N?
编辑:添加updateDirection()
方法
为了更好地理解此方法,请查看此图像:
public static int updateDirection(int direction, int i, int j, int n) {
/** if on the secondary diagonal direction is 1 or 3 */
if(i+j==n-1)
direction++;
/** if on the lower half of the main diagonal, direction is 2 */
if(i==j && j+j>=n)
direction++;
/** if on the row below the higher half of the main diagonal, direction is 0 */
if(i==j+1 && i+j<n)
direction++;
/** in other cases, direction doesn't change */
return direction%4;
}
Edit2:这是我的测试方法:
public static void testSpiral(){
for(int n=0; n<=5; n++)
System.out.println(Arrays.deepToString(spiral(n)));
}
Edit3 :updateRow()
并updateColoumn()
添加了方法:
public static int updateRow(int i, int direction) {
int res;
if(direction==1)
res=i+1; //moves from top to bottom
else
res = i-1; //moves from bottom to top
return res;
}
public static int updateColoumn(int j, int direction){
int res;
if(direction==0)
res=j+1; //moves from left to right
else
res=j-1; //moves from right to left
return res;