题目:
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]
You should return [1,2,3,6,9,8,7,4,5]
.
需要注意下面的一行的答应顺序
#include <iostream>
#include <vector>
using namespace std;
void SpiralMatrix(vector<vector<int> >& vec)
{
int m=vec.size(); // 行
int n=vec[0].size(); //列
int i,j,tmp,k;
for(i=0;i<(m+1)/2;i++)
{
for(j=i;j<n-i;j++)
cout<<vec[i][j]<<" ";
for(j=j-1,k=i+1;k<m-i;k++)
cout<<vec[k][j]<<" ";
for(k=k-1,j=j-1;k!=i&&j>=i;j--)
cout<<vec[k][j]<<" ";
for(j=k-1;j>i;j--)
cout<<vec[j][i]<<" ";
}
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);
}
for(i=0;i<image.size();i++)
{
for(j=0;j<vec.size();j++)
cout<<image[i][j]<<" ";
cout<<endl;
}
cout<<"====================="<<endl;
SpiralMatrix(image);
return 0;
}