- 题目描述
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].
2. 解题思路
题目大概意思就是回型输出一个矩阵,在这里我的想法是模拟粒子的移动,粒子运动不得超出边框,每次到达边框边框就会缩小。
初始位置: (0,0)
初始速度:iv=0,jv=1;(向右走)
初始边界:int upb=-1,lowb=matrix.size(),leftb=-1,rightb=matrix[0].size();
边界的变化情况:
(1) 到达上边界,则左边界++
(2) 到达下边界,则右边界–
(3) 到达左边界,则下边界–
(4) 到达右边界,则上边界++
3. 实现代码
class Solution {
public:
vector<int> spiralOrder(vector<vector<int> >& matrix) {
vector <int> res;
if(matrix.size()==0)
return res;
int i=0,j=0;
int iv=0,jv=1;
int upb=-1,lowb=matrix.size(),leftb=-1,rightb=matrix[0].size();
int count=0;
while(1){
if(count==matrix.size()*matrix[0].size())
break;
//cout<<matrix[i][j]<<"---"<<count<<endl;;
res.push_back(matrix[i][j]);
++count;
int ti=i,tj=j;
if(ti+iv==lowb){
iv=0;
jv=-1;
--rightb;
}
else if(ti+iv==upb){
iv=0;
jv=1;
++leftb;
}
else if(tj+jv==rightb){
iv=1;
jv=0;
++upb;
}
else if(tj+jv==leftb){
iv=-1;
jv=0;
--lowb;
}
i+=iv;
j+=jv;
}
return res;
}
};