一、题目
给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/spiral-matrix
二、解题思路
用四个变量作为四个方向的边界,沿着矩阵边界进行顺时针遍历,每遍历一条边界上的数据,对应的边界就往中间进行收缩,直至其中两个方向的边界相等,遍历结束。
三、程序
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int len1 = matrix.size();
int len2 = matrix[0].size();
vector<int> ans;
int top = 0, left = 0, right = len2 -1, bottom = len1 -1; //控制四条边界
while(top <= bottom && left <= right){
int ltor = left;
while(ltor <= right){ //上边 左→右
ans.push_back(matrix[top][ltor]);
ltor++;
}
top++;
if(top > bottom) break;
int ttob = top;
while(ttob <= bottom){ //右边 上→下
ans.push_back(matrix[ttob][right]);
ttob++;
}
right--;
if(right < left) break;
int rtol = right;
while(rtol >= left){ //下边 右→左
ans.push_back(matrix[bottom][rtol]);
rtol--;
}
bottom--;
if(bottom < top) break;
int btot = bottom;
while(btot >= top){ //左边 下→上
ans.push_back(matrix[btot][left]);
btot--;
}
left++;
}
return ans;
}
};