1. 程式人生 > 其它 >【LeetCode:遞迴與回溯】:54.螺旋矩陣

【LeetCode:遞迴與回溯】:54.螺旋矩陣

技術標籤:LeetCode

54.螺旋矩陣

難度:中等


給定一個包含 m x n 個元素的矩陣(m 行, n 列),請按照順時針螺旋順序,返回矩陣中的所有元素。

示例 1:

輸入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
輸出: [1,2,3,6,9,8,7,4,5]
示例 2:

輸入:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
輸出: [1,2,3,4,8,12,11,10,9,5,6,7]


題解

/**
 * @param {number[][]} matrix
 * @return {number[]}
 */
var spiralOrder = function (matrix) { if (matrix.length == 0) return []; const res = []; let top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1 while (top <= bottom && left <= right) { for (let i = left; i <= right; i++) res.push(matrix[top][i]
) top++; for (let i = top; i <= bottom; i++) res.push(matrix[i][right]) right--; if (top > bottom || left > right) break; for (let i = right; i >= left; i--) res.push(matrix[bottom][i]) bottom--; for (let i = bottom; i >= top; i--) res.
push(matrix[i][left]) left++; } return res; };

分析

由題可知遍歷順序為順時針,而且可知
上邊界 top : 0
下邊界 bottom : matrix.length - 1
左邊界 left : 0
右邊界 right : matrix[0].length - 1
遍歷且需滿足
top<=bottom && left<=right;
當遍歷完上、左邊界,邊界值加1
遍歷完下、右邊界,邊界值減1