function SpiralMatrix( matrix ) {
// write code here
// 矩阵为空的情况
if(matrix.length === 0) return []
// 定义边界条件,分别是四个方向上下左右
let top = 0
let bottom = matrix.length - 1
let left = 0
let right = matrix[0].length - 1
// 旋转方向
let direction = "right"
// 定义一个接收答案的数组
let result = []
// 开始循环的条件,方向是右下左上
while(left<=right && top<=bottom){
// 方向向右时
if(direction === "right"){
for(let i=left;i<=right;i++){ // 循环遍历矩阵的top行
result.push(matrix[top][i]) // 将矩阵的top行中的每一个元素都push到result数组
}
top++
direction = "down" // 将方向改为向下
}
// 方向向下时
else if(direction === "down"){
for(let i=top;i<=bottom;i++){ // 循环遍历矩阵的right列
result.push(matrix[i][right]) // 将矩阵的right列中的每一个元素都push到result数组
}
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
}