/*
54. Spiral Matrix My Submissions QuestionEditorial Solution
Total Accepted: 57679 Total Submissions: 256710 Difficulty: Medium
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].
Subscribe to see which companies asked this question
Show Tags
Show Similar Problems
*/
/*
解题思路:
分上行->右列->下行->左列
维持四个变量 left right up down
结束条件是:if(left>right || up>down)
*/
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> res;
//如果空矩阵,则返回
if(matrix.size()==0||matrix[0].size()==0)return res;
//定义四个变量
int left=0,right=matrix[0].size()-1,up=0,down=matrix.size()-1;
//大循环
while(left<=right&&up<=down){
//最上边一行(从左到右)
for(int i=left;i<=right;i++){
res.push_back(matrix[up][i]);
}
++up;
//最右侧一列(从上到下)
for(int i=up;i<=down;i++){
res.push_back(matrix[i][right]);
}
--right;
//最下边一行(从右到左)
if(left>right||up>down)break;
for(int i=right;i>=left;i--){
res.push_back(matrix[down][i]);
}
--down;
//最左侧一列(从下到上)
if(left>right||up>down)break;
for(int i=down;i>=up;i--){
res.push_back(matrix[i][left]);
}
++left;
}
return res;
}
};