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:
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].
思路:用两层嵌套的循环,内层循环打印矩阵的一圈,外层循环打印矩阵的所有圈。
vector<int> spiralOrder(vector<vector<int> > &matrix) {
vector<int> vec;
if(matrix.size()==0)
return vec;
int left = -1, right = matrix[0].size()-1; // left and right boundaries, inclusive
int top = 0, bottom = matrix.size()-1; // top and bottom boundaries, inclusive
int i=-1, j=0; // matrix[i][j] is the element that will be put to output
while(1)
{
i++; // note that both i++, because previous i is out of valid scope
left++;
if(left<=right)
for(j=left; j<=right; j++)
vec.push_back(matrix[i][j]);
else
break;
j--; // note j-- because of the previous value of j is out of valid scope
top++;
if(top<=bottom)
for(i=top; i<=bottom; i++)
vec.push_back(matrix[i][j]);
else
break;
i--;
right--;
if(left<=right)
for(j=right; j>=left; j--)
vec.push_back(matrix[i][j]);
else
break;
j++;
bottom--;
if(top<=bottom)
for(i=bottom; i>=top; i--)
vec.push_back(matrix[i][j]);
else
break;
}
return vec;
}