用java打印螺旋矩阵
我正在尝试使用接受整数的方法来打印螺旋矩阵。然而,我在纸上的代码工作正常,但是当我运行时,我得到不同的数字来代替我想要的数字。
public class ConstructSpiral{
public static void main(String[] args) {
constructSpiral(3);
}
public static int[][] constructSpiral(int n) {
int[][] matrix = new int[n][n];
int sum = 0;
int i = matrix.length - 1;
int j = matrix[i].length - 1;
for(j = matrix[i].length - 1; j >= 0; j--)
{
sum += sum + 1;
matrix[i][j] = sum;
}
j = 0;
for(i = (matrix.length - 1) - 1; i >= 0; i--) {
sum += sum + 1;
matrix[i][j] = sum;
}
i = 0;
for(j = 1; j < matrix.length; j++)
{
sum += sum + 1;
matrix[i][j] = sum;
}
i = 1;
for(j = 2; j <= i; j--){
sum += sum + 1;
matrix[i][j] = sum;
}
for(i = matrix.length - 1; i >= 0; i--) {
for(j = matrix[i].length - 1; j >= 0; j--)
{
System.out.print(matrix[i][j] + ", ");
}
System.out.println();
}
return matrix;
}
}
实际上,它应该打印类似
5 6 7
4 9 8
3 2 1
In help 的内容,我们将不胜感激。
I'm trying to print a spiral matrix using a method that takes in an integer. However, my code on paper works fine, but when I run I get different numbers in place of the number I want.
public class ConstructSpiral{
public static void main(String[] args) {
constructSpiral(3);
}
public static int[][] constructSpiral(int n) {
int[][] matrix = new int[n][n];
int sum = 0;
int i = matrix.length - 1;
int j = matrix[i].length - 1;
for(j = matrix[i].length - 1; j >= 0; j--)
{
sum += sum + 1;
matrix[i][j] = sum;
}
j = 0;
for(i = (matrix.length - 1) - 1; i >= 0; i--) {
sum += sum + 1;
matrix[i][j] = sum;
}
i = 0;
for(j = 1; j < matrix.length; j++)
{
sum += sum + 1;
matrix[i][j] = sum;
}
i = 1;
for(j = 2; j <= i; j--){
sum += sum + 1;
matrix[i][j] = sum;
}
for(i = matrix.length - 1; i >= 0; i--) {
for(j = matrix[i].length - 1; j >= 0; j--)
{
System.out.print(matrix[i][j] + ", ");
}
System.out.println();
}
return matrix;
}
}
In reality, it should print something like
5 6 7
4 9 8
3 2 1
In help would greatly be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您走在正确的轨道上,您可能只想多利用
constructSpiral
方法的n
参数,并将打印逻辑移至不同的方法中:用法示例 1:
用法示例 2:
用法示例 3:
I think you are on the right track you might just want to utilize the
n
parameter of yourconstructSpiral
method a bit more, as well as move the printing logic into a different method:Example Usage 1:
Example Usage 2:
Example Usage 3: