|
| 1 | +/** |
| 2 | + * Key: Traverse from left to right, increase rowStart, means this top row has been visited. |
| 3 | + * Traverse from up to down, decrease colEnd, means this right column has been visited. |
| 4 | + * Traverse from right to left, decrease rowEnd, means this bottom row has been visited. |
| 5 | + * Traverse from down to up, increase colStart, means this left column has been visited. |
| 6 | + * when the rowStart === rowEnd, there is only this row left to visit, (left -> right) |
| 7 | + * when the colStart === colEnd, there is only this column left to visit, (up -> down) |
| 8 | + * |
| 9 | + *@param {number[][]} matrix |
| 10 | + *@return {number[]} |
| 11 | + */ |
| 12 | +varspiralOrder=function(matrix){ |
| 13 | +if(matrix.length===0)returnmatrix; |
| 14 | +varrowStart=0; |
| 15 | +varcolStart=0; |
| 16 | +varrowEnd=matrix.length-1; |
| 17 | +varcolEnd=matrix[rowStart].length-1; |
| 18 | +varpath=[]; |
| 19 | + |
| 20 | +while(rowStart<=rowEnd&&colStart<=colEnd){ |
| 21 | +if(rowStart===rowEnd){ |
| 22 | +for(vari=colStart;i<=colEnd;i++){ |
| 23 | +path.push(matrix[rowStart][i]); |
| 24 | +} |
| 25 | +break; |
| 26 | +} |
| 27 | + |
| 28 | +if(colStart===colEnd){ |
| 29 | +for(vari=rowStart;i<=rowEnd;i++){ |
| 30 | +path.push(matrix[i][colEnd]); |
| 31 | +} |
| 32 | +break; |
| 33 | +} |
| 34 | + |
| 35 | +for(vari=colStart;i<=colEnd;i++){ |
| 36 | +path.push(matrix[rowStart][i]); |
| 37 | +} |
| 38 | +rowStart++; |
| 39 | + |
| 40 | +for(vari=rowStart;i<=rowEnd;i++){ |
| 41 | +path.push(matrix[i][colEnd]); |
| 42 | +} |
| 43 | +colEnd--; |
| 44 | + |
| 45 | +for(vari=colEnd;i>=colStart;i--){ |
| 46 | +path.push(matrix[rowEnd][i]); |
| 47 | +} |
| 48 | +rowEnd--; |
| 49 | + |
| 50 | +for(vari=rowEnd;i>=rowStart;i--){ |
| 51 | +path.push(matrix[i][colStart]); |
| 52 | +} |
| 53 | +colStart++; |
| 54 | +} |
| 55 | + |
| 56 | +returnpath; |
| 57 | +}; |