难度:简单
题目描述:
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字
示例:
输入: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 - 1const size = matrix.length * matrix[0].lengthwhile (res.length !== size) { // 仍未遍历结束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 (res.length === size) 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};
var spiralOrder = function (matrix) {if (matrix.length == 0) return []const res = []let top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1while (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) breakfor (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};
