Spiral Matrix II

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

For example,
Given n = 3,

You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
     vector<int>vec(n,0);
     vector<vector<int>>res(n,vec);
     int i=0,j=0,m=1;

     while(m<=n*n)
     {
         while(j<n)
         {

             if( res[i][j]==0)
             {
             res[i][j]=m;
             m++;
             j++;
             }
             else
               break;
         }
         i++;
         j--;
         while(i<n)
         {
             if( res[i][j]==0)
             {
                res[i][j]=m;
                 m++;
                 i++;
             }
             else
               break;
         }
         j--;
         i--;
           while(j>=0&&i<n&&j<n)
         {
             if( res[i][j]==0)
             {
                 res[i][j]=m;
                 m++;
                 j--;
             }
             else 
             break;
         }
        i--;
        j++;
          while(i>=0&&i<n&&j<n)
         {
             if( res[i][j]==0)
             {
             res[i][j]=m;
             m++;
             i--;
             }
             else
             break;
         }
        j++;
        i++;
     }
     return res;
    }
};

你可能感兴趣的:(Spiral Matrix II)