题目
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
示例 2:
输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]
限制:
0 <= matrix.length <= 100
0 <= matrix[i].length <= 100
思路:不断沿着四条边界遍历,缩小边界值
- 时间复杂度:O(MN),需要遍历二维数组的每一个数
- 空间复杂度:O(1),除了保存结果之外其余辅助空间为O(1)
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> anws;
if( matrix.size()==0 ){
return anws;
}
//初始化边界
int left = 0;
int right = matrix[0].size()-1;
int top = 0;
int bottom = matrix.size()-1;
//按照顺时针方向沿着4条边界遍历,遍历完记得更新边界且判断边界,一旦出界则终止遍历
int i;
while( true ){
//从左到右:[top,left...right]
for(i=left; i<=right; i++){
anws.push_back(matrix[top][i]);
}
top++;
if( top > bottom )
break;
//从上到下:[top...bottom,right]
for(i=top; i<=bottom; i++){
anws.push_back(matrix[i][right]);
}
right--;
if( right < left )
break;
//从右到左:[botttom, right...left]
for(i=right; i>=left; i--){
anws.push_back(matrix[bottom][i]);
}
bottom--;
if( bottom < top )
break;
//从下到上:[bottom...top, left]
for(i=bottom; i>=top; i--){
anws.push_back(matrix[i][left]);
}
left++;
if( left > right )
break;
}
return anws;
}
};