leetcode(59)螺旋矩阵2

螺旋矩阵2

解题思路:

class Solution {
    public int[][] generateMatrix(int n) {
        int[][] matrix = new int[n][n];
        int count = 0;
        int p = 0;
        int q = n-1;
        int s = n-1;
        int t = 0;
        while(p<=s&&t<=q){
            for(int i=t;i<=q;++i){
                matrix[p][i] = ++count;
            }
            ++p;
            for(int i=p;i<=s;++i){
                matrix[i][q] = ++count;
            }
            --q;
            for(int i=q;i>=t;--i){
               matrix[s][i] = ++count; 
            }
            --s;
            for(int i=s;i>=p;--i){
               matrix[i][t] = ++count;  
            }
            ++t;
        }
        return matrix;
    }
}

 

posted @ 2019-07-26 19:30  海平面下的我们  阅读(91)  评论(0编辑  收藏  举报