螺旋顺序的二维数组 [英] 2d Array in Spiral Order
本文介绍了螺旋顺序的二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试按螺旋顺序填充数组.到目前为止,我可以按螺旋顺序打印数组,但是有没有办法修改数组,以便我可以按螺旋顺序填充它,然后只打印数组?我希望它像倒计时一样按降序排列.请帮忙!
I'm trying to fill an array in spiral order. So far, I can print the array in spiral order, but is there a way to modify the array so that i can fill it in spiral order and then just print the array? I'd like it to go in decreasing order like a countdown. Please help!
public class Spiral {
public static void main(int m, int n) {
// create m by n array of integers 1 through m*n
int[][] values = new int[m][n];
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
values[i][j] = 1 + (m*n)*i + j;
// spiral
for (int i = (m*n)-1, j = 0; i > 0; i--, j++) {
for (int k = j; k < i; k++) System.out.println(values[j][k]);
for (int k = j; k < i; k++) System.out.println(values[k][i]);
for (int k = i; k > j; k--) System.out.println(values[i][k]);
for (int k = i; k > j; k--) System.out.println(values[k][j]);
}
}
}
推荐答案
下面的函数是一个大小为 N × N 的方阵,其中包含从 1 到 N * N 的整数,按螺旋顺序从左上角开始顺时针方向方向.
Below function is a square matrix with a size N × N containing integers from 1 to N * N in a spiral order, starting from top-left and in clockwise direction.
int[][] spiralNumbers(int n) {
int[][] matrix = new int[n][n];
for (int step = 0, a = 0, size; step < n/2; step++) {
size = (n - step * 2 - 1);
for (int i = 0, chunk, chunkIndex, chunkOffset; i < 4 * size; i++) {
chunk = i / size;
chunkIndex = i % size;
chunkOffset = n - step - 1;
switch (chunk) {
case 0:
matrix[step][chunkIndex + step] = a+1;
break;
case 1:
matrix[chunkIndex + step][chunkOffset] = a+1;
break;
case 2:
matrix[chunkOffset][chunkOffset - chunkIndex] = a+1;
break;
case 3:
matrix[chunkOffset - chunkIndex][step] = a+1;
break;
default:
throw new IndexOutOfBoundsException();
}
a++;
}
if (n % 2 == 1) {
matrix[n/2][n/2] = n * n;
}
}
return matrix;
}
这篇关于螺旋顺序的二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文