螺旋顺序的二维数组
我正在尝试按螺旋顺序填充数组。 到目前为止,我可以按螺旋顺序打印数组,但是有没有办法修改数组,以便我可以按螺旋顺序填充它,然后只打印数组? 我希望它像倒计时一样按降序排列。 请帮忙!
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]);
}
}
}
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]);
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
下面的函数是一个大小为 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.
如果您已经找到了执行读取(用于打印)的代码,那么您肯定可以使用相同的逻辑修改它来执行写入操作?
如果您希望矩阵中的每个单元格都包含其“顺序号”,向后计数,假设您的访问逻辑是正确的,类似这样的事情应该可以工作:
If you've figured out code to do the reads (for printing), then surely you can just modify that to do writes instead, using the same logic?
If you want each cell in the matrix to contain its "sequential number", counting backwards, something like this ought to work, assuming your access logic is correct:
不是最有效的,但它应该可以工作:g 是数组。 我还使用异常来控制逻辑。
Not the most efficient, but it should work: g is the array. I'm also using exceptions to control logic.
以下是一些变化:
Here is some of the variations:
}
}
这是我对此的看法:
Here's my take on this: