[LeetCode][JavaScript]Spiral Matrix
Spiral Matrix
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]
You should return [1,2,3,6,9,8,7,4,5]
.
https://leetcode.com/problems/spiral-matrix/
旋转抱歉。
开四个变量,代表剩余矩形长度的开始、结束和宽度的开始、结束。
四个值圈定了一个范围(也可以理解为两个点四个坐标:左上角X,Y和右下角X,Y,四个坐标确定一个矩形)。
一开始高度从0到matrix.length,长度从0到matrix[0].length。
每计算一边,缩小对应的长度或宽度的范围。
1 /** 2 * @param {number[][]} matrix 3 * @return {number[]} 4 */ 5 var spiralOrder = function(matrix) { 6 var res = [], i; 7 var m = matrix.length, n = (m === 0 ? 0 : matrix[0].length); 8 var heightStart = 0, heightEnd = m - 1, widthStart = 0, widthEnd = n - 1; 9 while(heightStart <= heightEnd && widthStart <= widthEnd){ 10 for(i = widthStart; i <= widthEnd; i++){ 11 res.push(matrix[heightStart][i]); 12 } 13 heightStart++; 14 for(i = heightStart; i <= heightEnd; i++){ 15 res.push(matrix[i][widthEnd]); 16 } 17 widthEnd--; 18 if(heightStart <= heightEnd){ 19 for(i = widthEnd; i >= widthStart; i--){ 20 res.push(matrix[heightEnd][i]); 21 } 22 heightEnd--; 23 } 24 if(widthStart <= widthEnd){ 25 for(i = heightEnd; i >= heightStart; i--){ 26 res.push(matrix[i][widthStart]); 27 } 28 widthStart++; 29 } 30 } 31 return res; 32 };