题目描述:
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]
.
按照顺时针螺旋形遍历矩阵定义四个变量分别表示当前未遍历对子矩阵对上下左右边界,每次遍历则进行右->下->左->上四次循环,将遍历的元素加入结果中,同时调整上下左右边界,循环的条件是左边界小于等于右边界,上边界小于等于下边界。
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> result;
if(matrix.size()==0||matrix[0].size()==0) return result;
int m=matrix.size();
int n=matrix[0].size();
int right_bottom=n-1;
int left_bottom=0;
int down_bottom=m-1;
int up_bottom=0;
while(left_bottom<=right_bottom&&up_bottom<=down_bottom)
{
//right
for(int i=left_bottom;i<=right_bottom;i++) result.push_back(matrix[up_bottom][i]);
up_bottom++;
//down
for(int i=up_bottom;i<=down_bottom;i++) result.push_back(matrix[i][right_bottom]);
right_bottom--;
//left,之前对up_bottom有修改,可能会超过down_bottom
if(up_bottom<=down_bottom)
{
for(int i=right_bottom;i>=left_bottom;i--) result.push_back(matrix[down_bottom][i]);
down_bottom--;
}
//up,之前对right_bottom有修改,可能会超过left_bottom
if(left_bottom<=right_bottom)
{
for(int i=down_bottom;i>=up_bottom;i--) result.push_back(matrix[i][left_bottom]);
left_bottom++;
}
}
return result;
}
};