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) { // Start typing your C/C++ solution below // DO NOT write int main() function vector<vector<int>> res(n,vector<int>(n)); int lays = (n+1)/2; bool single = n%2; int num = 1; for(int lay = 0; lay < lays; lay ++){ int topRow = lay; int rightColumn = n - 1 - lay; //process the top for(int i = lay; i <= rightColumn; i++) res[topRow][i] = num++; //process the right Column for(int i = lay+1; i <= rightColumn ;i++) res[i][rightColumn] = num++; if(lay == lays -1 && single ) continue; //process the bottom for(int i = rightColumn - 1; i>= lay; i--) res[rightColumn][i] = num++; for(int i = rightColumn - 1; i> lay ;i--) res[i][lay] = num++; } return res; } };