アイデアは次のとおりです。最初に右に移動し、次に上++(次に次のレベルに移動)、次に下、右–、左、下–、上、左++に移動すると、画像が理解しやすくなります。
/**
* @param {number[][]} matrix
* @return {number[]}
*/
var spiralOrder = function(matrix) {
if(matrix.length==0){
return []
}
var result=[]
let top=0
let right=matrix[0].length-1
let bottom=matrix.length-1
let left=0
while(true){
for(var l=left;l<=right;l++){
result.push(matrix[top][l])
}
top++;
if(top>bottom){
break
}
console.log(top)
for(var t=top;t<=bottom;t++){
console.log(matrix[t][right])
result.push(matrix[t][right])
}
right--;
if(left>right){
break
}
for(var r=right;r>=left;r--){
result.push(matrix[bottom][r])
}
bottom--;
if(top>bottom){
break
}
for(var b=bottom;b>=top;b--){
result.push(matrix[b][left])
}
left++
if(left>right){
break
}
}
return result;
};