题目:
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3
,
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
思路:和上一道题目类似,只不过这里需要赋值,在螺旋遍历数组时,采用的方法是先上,再右,再下,再左,在遍历上时需要遍历到底,然后遍历左,往下走一层遍历左,然后遍历到底,然后遍历下,遍历下的时候需要往上走一层,这个时候需要注意了,因为在遍历左时是往下走了一层,这个时候往上走一层,需要判断不是和遍历上的时候同一层,然后遍历左。遍历下和遍历上是否同一层需要注意。
<pre name="code" class="cpp">void SpiralMatrixII(int num)
{
vector<int> tmp(num,0);
vector<vector<int> > vec(num,tmp);
int m=num; // 行
int n= num; //列
int i,j,k;
int count=1;
for(i=0;i<(m+1)/2;i++)
{
for(j=i;j<n-i;j++)
vec[i][j] = count++;
for(j=j-1,k=i+1;k<m-i;k++)
vec[k][j] = count++;
for(k=k-1,j=j-1;k!=i&&j>=i;j--)
vec[k][j]=count++;
for(j=k-1;j>i;j--)
vec[j][i] = count++;
}
for(i=0;i<vec.size();i++)
{
for(j=0;j<vec[i].size();j++)
cout<<vec[i][j]<<" ";
cout<<endl;
}
cout<<endl;
}
int main()
{
vector<int> vec(6,0);
vector<vector<int> > image;
int i,j;
for(i=0;i<7;i++)
{
for(j=0;j<vec.size();j++)
vec[j] = i+j+1;
image.push_back(vec);
}
SpiralMatrixII(6);
cout<<"====================="<<endl;
return 0;
}