059 Spiral Matrix II 旋转打印矩阵 II

给出正整数 n,生成正方形矩阵,矩阵元素为 1 到 n2 ,元素按顺时针顺序螺旋排列。
例如,
给定正整数 n = 3,
应返回如下矩阵:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]
详见:https://leetcode.com/problems/spiral-matrix-ii/description/

Java实现:

class Solution {
    public int[][] generateMatrix(int n) {
        int[][] res=new int[n][n];
        if(n==0){
            return res;
        }
        int top=0;
        int bottom=n-1;
        int left=0;
        int right=n-1;
        int num=1;
        while(top<=bottom&&left<=right){
            if(num<=n*n){
                for(int j=left;j<=right;++j){
                    res[top][j]=num;
                    ++num;
                }
            }
            ++top;
            if(num<=n*n){
                for(int i=top;i<=bottom;++i){
                    res[i][right]=num;
                    ++num;
                }
            }
            --right;
            if(num<=n*n){
                for(int j=right;j>=left;--j){
                    res[bottom][j]=num;
                    ++num;
                }
            }
            --bottom;
            if(num<n*n){
                for(int i=bottom;i>=top;--i){
                    res[i][left]=num;
                    ++num;
                }
            }
            ++left;
        }
        return res;
    }
}

posted on 2018-04-02 23:23  lina2014  阅读(99)  评论(0编辑  收藏  举报

导航