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

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

技術標籤:LeetCode

59.螺旋矩陣II

難度:中等


給定一個正整數 n,生成一個包含 1 到 n2 所有元素,且元素按順時針順序螺旋排列的正方形矩陣。

示例:

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


題解

/**
 * @param {number} n
 * @return {number[][]}
 */
var generateMatrix = function(n) {
  let _result = Array.from({ length: n }, () => Array(n))
    let num =
1, top=0, bottom = n - 1, // 行尾邊界 left = 0, // 列首邊界 right = n - 1 // 列尾邊界 while (num <= n * n) { // 首行 for (let i = left; i <= right; i++) { _result[top][i] = num++ } top++ // 尾列 for (let i = top; i <= bottom;
i++) { _result[i][right] = num++ } right-- // 尾行 for (let i = right; i >= left; i--) { _result[bottom][i] = num++ } bottom-- // 首列 for (let i = bottom; i >= top; i--) { _result[i][left] = num++ }
left++ } return _result };

分析

由題可知遍歷順序為順時針,而且可知
上邊界 top : 0
下邊界 bottom : n - 1
左邊界 left : 0
右邊界 right : n - 1
開始num為1
遍歷且需滿足
num<=n*n
當遍歷完上、左邊界,邊界值加1
遍歷完下、右邊界,邊界值減1