JavaScript:leetcode_面試題29. 順時針打印矩陣(分層 + 遞歸)

題目說明

輸入一個矩陣,按照從外向裏以順時針的順序依次打印出每一個數字。

 

示例 1:

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

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

限制:

0 <= matrix.length <= 100
0 <= matrix[i].length <= 100
注意:本題與主站 54 題相同:https://leetcode-cn.com/problems/spiral-matrix/

解題思路一(分層+遞歸)

  1. 首先明白題意,題目給出的示例數組是平鋪的,不是特別清晰,可能短時間反應不過來它是想幹嘛,我們先轉換一下.
 [
 [1,2,3],
 [4,5,6],
 [7,8,9]
 ]
 1 -> 2 -> 3 -> 6 -> 9 -> 8 -> 7 -> 4 -> 5

 矩形外圍開始,順時針輸出.
  1. 因爲是從外層開始順時針的,所以我們先看最外層的我們如何得到.
    1. 首先最外層相當於一個正方形的四條邊.(我們將頂點放入上下兩條邊)
    2. top: [2], 加入左上和右上兩個頂點爲[1, 2, 3]
    3. right: [6]
    4. bottom: [8], 加入左下和右下兩個頂點爲 [7, 8, 9]
    5. left: [4]
    6. 結果[1,2,3,6,9,8,7,4,5] 其中left, bottom 需要反轉過來.(因爲順時針)
  2. 剝離之後,原來的矩形只剩下了[[5]], 假若我們矩形是多層的, 那麼剩下來的仍然是個矩形,那麼我們就可以將剩下的矩陣重新傳入, 重複上面第二步求出top right bottom left

代碼實現一

/**
 * @param {number[][]} matrix
 * @return {number[]}
 */
var spiralOrder = function(matrix) {
    if (matrix.length <= 1) {
        return matrix[0] || [];
    }
    if (matrix[0].length <= 1) {
        return matrix.reduce(function(sum, item) {
            return [...sum, ...item];
        }, [])
    }
    let top = matrix.shift();
    let right = [], left = [];
    for (let i = 0; i < matrix.length; i++) {
        right.push(matrix[i].pop());
        left.unshift(matrix[i].shift());
    }
    let bottom = matrix.pop().reverse();
    let res = [...top, ...right, ...bottom, ...left];
    return res.concat(spiralOrder(matrix));
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章