https://leetcode-cn.com/problems/spiral-matrix/
点击查看【bilibili】
题目
给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
示例

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

输入:[[1, 2, 3, 4],[5, 6, 7, 8],[9,10,11,12]]输出: [1,2,3,4,8,12,11,10,9,5,6,7]
解答

1.如果数组为空,返回空数组
2.定义4个边界以及当前方向(direction)
3.当左边界小于等于右边界,且上边界小等于下边界时,执行 while循环:
按照右,下,左,上的顺序,依欠将路径上的字符添加到结果里
4. while循环结束后,返回结果

为什么left<=right && top <= bottom ?
考虑边界问题
答案
var spiralOrder = function (matrix) {if (matrix.length === 0) return [];let left = 0let right = matrix[0].length - 1let top = 0let bottom = matrix.length - 1let direction = 'right'let result = []/**[ 1, 2, 3 ],[ 4, 5, 6 ],[ 7, 8, 9 ]*/while (left <= right && top <= bottom) {if (direction === 'right') {for (let i = left; i <= right; i++) {result.push(matrix[top][i])}top++direction = 'down'} else if (direction === 'down') {for (let i = top; i <= bottom; i++) {result.push(matrix[i][right])}right--direction = 'left'} else if (direction === 'left') {for (let i = right; i >= left; i--) {result.push(matrix[bottom][i])}bottom--direction = 'top'} else if (direction === 'top') {for (let i = bottom; i >= top; i--) {result.push(matrix[i][left])}left++direction = 'right'}}return result};
