You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Given an m x n matrix, return all elements of the matrix in spiral order.
/** * @param {number[][]} matrix * @return {number[]} */varspiralOrder=function(matrix){constres=[];letstartRow=0,endRow=matrix.length-1,startCol=0,endCol=matrix[0].length-1;while(startRow<=endRow&&startCol<=endCol){//traverse every column [[0,0], [0,1], [0,2]....] so we can add the first rowfor(letcol=startCol;col<=endCol;col++){res.push(matrix[startRow][col]);}//traverse the second side, so start from the 2nd row because the first row is alredy in stack.for(letrow=startRow+1;row<=endRow;row++){res.push(matrix[row][endCol]);}for(letcol=endCol-1;col>=startCol;col--){if(startRow===endRow)break;res.push(matrix[endRow][col]);}for(letrow=endRow-1;row>startRow;row--){if(startCol===endCol)break;res.push(matrix[row][startCol])}startRow++;endRow--;startCol++;endCol--;}returnres;};