54. Spiral Matrix

Leetcode

題目

Given an m x n matrix, return all elements of the matrix in spiral order.

解答

  • 方法一

每次都加入第一列,然後逆時針旋轉矩陣 90 度,再依次加入第一列

var spiralOrder = function(matrix) {
    var rotate = function(matrix) {
      const m = matrix.length;
      const n = matrix[0].length;
      const result = Array.from({length: n}, () => []);
      for(let i=0; i<m; i++) {
        for(let j=0; j<n; j++) {
          result[j].push(matrix[i][n-j-1]);
        }
      }

      return result
    }; 

    const result = [];
    while(matrix.length) {
      const next = matrix.splice(0, 1)[0];
      result.push(...next);
      if (matrix.length) {
        matrix = rotate(matrix);
      }
    }

    return result;
};

Runtime: 68 ms, faster than 88.47% of JavaScript online submissions for Spiral Matrix.

Memory Usage: 38.6 MB, less than 37.64% of JavaScript online submissions for Spiral Matrix.

  • 方法二

設定四個方向(往右 -> 往下 -> 往左 -> 往上),依序遍歷

Runtime: 68 ms, faster than 88.31% of JavaScript online submissions for Spiral Matrix.

Memory Usage: 38.9 MB, less than 18.59% of JavaScript online submissions for Spiral Matrix.

https://www.youtube.com/watch?v=HnP-pJLFZwYarrow-up-right

測資

參考資料

Last updated