LeetCode 59. Spiral Matrix II

题目

水题一枚

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        
        
        int i=0,j=0;
        
        vector<vector<int>> matrix;
        
        if(n==0)
            return matrix;
        
        for(int i=0;i<n;i++)
        {
            vector<int> ans;
            for(int j=0;j<n;j++)
            {
                ans.push_back(0);
            }
            matrix.push_back(ans);
        }
        
        
        int posi=1;
        int posj=0;
        int pos=1;
        int e=n;
        int s=n;
        while(true)
        {
            while(j<e){
                
                matrix[i][j] =pos++;
                j++;
            }
            
            j--;
            
            int tag=0;
            i++;
            while(i<s){
                
                matrix[i][j] =pos++;
                i++;
                tag=1;
            }
            i--;
            j--;
            while(j>=posj&&tag>=1)
            {
                matrix[i][j] =pos++;
                j--;
                tag=2;
            }
            j++;
            i--;
           while(i>=posi&&tag>=2){
              
               matrix[i][j] =pos++;
                i--;
            }
            i++;
            
            //i++;
            j++;
            
            posi++;
            posj++;
            s--;
            e--;     
            
            if(s==i||e==j)
                break;
        }
        
        return matrix;
        
    }
};
posted @ 2019-09-06 14:15  Shendu.CC  阅读(89)  评论(0编辑  收藏  举报