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

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

codeType
输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]
提示:
- m == matrix.length
- n == matrix[i].length
- 1 <= m, n <= 10
- -100 <= matrix[i][j] <= 100
解法: 按照四个方向的规律轮流移动
ts
function spiralOrder(matrix: number[][]): number[] {
// 模拟该遍历,用stepX,stepY固定每次横移或者竖移的步数
// 每次横移以后stepX--
// 竖移动后stepY--
let stepX = matrix[0].length
let stepY = matrix.length - 1
const totalCount = matrix.length * matrix[0].length
let i = 0, j = -1
const res: number[] = []
let count = 0
while(count < totalCount){
// 向右移动
for(let k = 0; k < stepX; k++){
j++
res.push(matrix[i][j])
count++
}
stepX--
if(count >= totalCount) return res
// 向下移动
for(let k = 0; k < stepY; k++){
i++
res.push(matrix[i][j])
count++
}
stepY--
if(count >= totalCount) return res
// 向左移动
for(let k = 0; k < stepX; k++){
j--
res.push(matrix[i][j])
count++
}
stepX--
if(count >= totalCount) return res
// 向上移动
for(let k = 0; k < stepY; k++){
i--
res.push(matrix[i][j])
count++
}
stepY--
if(count >= totalCount) return res
}
return res
};