给定一个整数n,生成一个正方形矩阵,该矩阵以螺旋顺序填充从1到n ^ 2的元素。例如,给定n = 4,
[
[1、2、3、4],
[12、13、14、5],
[11,16,15,6],
[10、9、8、7]
]
Java解决方案1
public int[][] generateMatrix(int n) {
int total = n*n;
int[][] result= new int[n][n];
int x=0;
int y=0;
int step = 0;
for(int i=0;i
while(y+step
i++;
result[x][y]=i;
y++;
}
y--;
x++;
while(x+step
i++;
result[x][y]=i;
x++;
}
x--;
y--;
while(y>=0+step){
i++;
result[x][y]=i;
y--;
}
y++;
x--;
step++;
while(x>=0+step){
i++;
result[x][y]=i;
x--;
}
x++;
y++;
}
return result;}
最后,开发这么多年我也总结了一套学习Java的资料与面试题,如果你在技术上面想提升自己的话,可以关注我,私信发送领取资料或者在评论区留下自己的联系方式,有时间记得帮我点下转发让跟多的人看到哦。