54. 螺旋矩阵
一、思想
1、以顺时针的方向,上右下左的进行一轮迭代,如果一条边从头遍历到底,则下一条边遍历的起点随之变化。选择不遍历到底,可以减小横向、竖向遍历之间的影响。
2、然后像内层收缩,4条边的两端同时收窄 1。进行第二轮迭代 3、循环终止的条件是 left < right && top < bottom 4、当终止的时候,只有一列的时候,就从左往右的进行遍历。只有一行的时候,就从上往下的进行遍历。
二、代码实现
var spiralOrder = function(matrix) {
// 定义矩阵四周的范围,这里是下标的范围
let left = 0, right = matrix[0].length-1,
top = 0, bottom = matrix.length-1;
// 存储结果
const res = []
// 进行遍历
while(top < bottom && left < right){
// 第一层迭代,不需要遍历到底
for(let i=left; i<right; i++) res.push(matrix[top][i]); // 上层
for(let i=top; i<bottom; i++) res.push(matrix[i][right]); // 右层
for(let i=right; i>left; i--) res.push(matrix[bottom][i]); // 下层
for(let i=bottom; i>top; i--) res.push(matrix[i][left]); // 左层
// 向内收缩
left++;
right--;
top++;
bottom--;
}
// 这里不需要while循环,因为只有最后一层
// 当只有一列的情况,从上至下进行遍历。注意这里需要遍历到底
if(left == right){
for(let i=top; i<=bottom;i++) res.push(matrix[i][left]);
}
// 只有一行的情况,从左往右进行遍历
else if(top == bottom){
for(let i=left; i<=right; i++) res.push(matrix[top][i]);
}
return res;
};