# 螺旋矩阵

  1. 螺旋矩阵

来源:力扣(LeetCode) 链接 (opens new window):https://leetcode.cn/problems/spiral-matrix/ 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

github (opens new window)

# 问题

给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素

输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]

# 思路

定义四个边界,依次遍历

var spiralOrder = function(matrix) {
if (matrix.length == 0) return [];
  const res = [];
  let top = 0,
    bottom = matrix.length - 1,
    left = 0,
    right = matrix[0].length - 1;
  while (top <= bottom && left <= right) {
    for (let i = left; i <= right; i++) res.push(matrix[top][i]);
    top++;
    for (let i = top; i <= bottom; i++) res.push(matrix[i][right]);
    right--;
    if (top > bottom || left > right) break;
    for (let i = right; i >= left; i--) res.push(matrix[bottom][i]);
    bottom--;
    for (let i = bottom; i >= top; i--) res.push(matrix[i][left]);
    left++;
  }
  return res;
};
陕ICP备20004732号-3