Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3,
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
这道题比spiral matrix要简单,因为是方阵,不需要判断越界情况,整体思路还是一样,实现四个函数,对应四条边的遍历
public class Solution {
public int[][] generateMatrix(int n) {
int num = n*n;
int [][]res = new int[n][n];
int a=1;
int s = 0;
while(a<=num){
for(int i=s;i<n;i++){
res[s][i]=a;
a++;
}
for(int i=s+1;i<n;i++){
res[i][n-1]=a;
a++;
}
for(int i=n-2;i>=s;i--){
res[n-1][i]=a;
a++;
}
for(int i=n-2;i>s;i--){
res[i][s]=a;
a++;
}
s++;
n--;
}
return res;
}
}
本文介绍了一个生成螺旋矩阵的算法,该算法针对n×n的方阵填充从1到n²的数字,并确保数字按螺旋顺序排列。通过四个方向的遍历实现,包括向右、向下、向左和向上,每一轮遍历完成后缩小边界继续下一轮,直至所有位置都被填满。
797

被折叠的 条评论
为什么被折叠?



