给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。

示例:

输入: 3
输出:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]

按每层来代码比较简单,但注意处理好特殊数据的问题,但是感觉代码比较挫

public int[][] generateMatrix(int n) {
    int[][] ret=new int[n][n];
    int count=1;
    for(int index=0;index<n/2;index++){
        for(j=index;j<=n-1-index;j++){
            ret[index][j]=count;
            count++;
        }
        for(int i=index+1;i<=n-1-index;i++){
            ret[i][n-index-1]=count;
            count++;
        }
        for(int j=n-2-index;j>index && n-1-index!=index;j--){
            ret[n-1-index][j]=count;
            count++;
        }
        for(int i=n-1-index;i>index && n-1-index!=index;i--){
            ret[i][index]=count;
            count++;
        }
    }
    return ret;
}

程浩
21 声望2 粉丝