Topic
Given an integer n, generate a square matrix filled with elements from 1 to N2 in Spiral order.
For example,
Given n = 3,
should return the following matrix:
[
[1, 2, 3],
[8, 9, 4],
[7, 6, 5]
] algorithm
Complexity: O (NM)
Class Solution {public:vector<vector<int> > Generatematrix (int n) {if (n==0) return vector<ve Ctor<int> > ();
Returns an empty array of vector<vector<int> > Ret (n,vector<int> (n,0));
int rowbegin=0;
int rowend=n-1;
int colbegin=0;
int colend=n-1;
int num=1;
while (rowbegin<=rowend && colbegin <= colend) {if (num<=n*n)//To determine whether the maximum value is reached {
Traverse to the right to add a for (int j=colbegin;j<=colend;j++) {ret[rowbegin][j]=num;
num++;
}} rowbegin++;
if (num<=n*n)//To determine whether the maximum is reached {///down traversal add for (int i=rowbegin;i<=rowend;i++) {
Ret[i][colend]=num;
num++;
}} colend--;
if (num<=n*n)//To determine whether the maximum value is reached {Walk to the left to add for (int j=colend;j>=colbegin;j--) {ret[rowend][j]=num;
num++;
}} rowend--;
if (num<=n*n)//To determine whether the maximum is reached {///Up traversal add for (int i=rowend;i>=rowbegin;i--) {
Ret[i][colbegin]=num;
num++;
}} colbegin++;
return ret; }
};