|
| 1 | +/* |
| 2 | +https://leetcode.com/problems/spiral-matrix/ |
| 3 | +
|
| 4 | +Given an m x n matrix, return all elements of the matrix in spiral order. |
| 5 | +
|
| 6 | +Example 1: |
| 7 | +Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] |
| 8 | +Output: [1,2,3,6,9,8,7,4,5] |
| 9 | +
|
| 10 | +Example 2: |
| 11 | +Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] |
| 12 | +Output: [1,2,3,4,8,12,11,10,9,5,6,7] |
| 13 | +
|
| 14 | +Constraints: |
| 15 | +m == matrix.length |
| 16 | +n == matrix[i].length |
| 17 | +1 <= m, n <= 10 |
| 18 | +-100 <= matrix[i][j] <= 100 |
| 19 | +*/ |
| 20 | + |
| 21 | +const RIGHT = "right"; |
| 22 | +const DOWN = "down"; |
| 23 | +const LEFT = "left"; |
| 24 | +const UP = "up"; |
| 25 | + |
| 26 | +const spiralOrder = (matrix) => { |
| 27 | + const result = []; |
| 28 | + // Can be: "right", "down", "left", "up" |
| 29 | + let direction = RIGHT; |
| 30 | + let offset = 0; |
| 31 | + let x = 0; |
| 32 | + let y = 0; |
| 33 | + |
| 34 | + while (true) { |
| 35 | + result.push(matrix[y][x]); |
| 36 | + |
| 37 | + if (direction == RIGHT) { |
| 38 | + if (x < matrix[0].length - 1 - offset) { |
| 39 | + x += 1; |
| 40 | + } else { |
| 41 | + direction = DOWN; |
| 42 | + y += 1; |
| 43 | + } |
| 44 | + } else if (direction === DOWN) { |
| 45 | + if (y < matrix.length - 1 - offset) { |
| 46 | + y += 1; |
| 47 | + } else { |
| 48 | + direction = LEFT; |
| 49 | + x -= 1; |
| 50 | + } |
| 51 | + } else if (direction === LEFT) { |
| 52 | + if (x > 0 + offset) { |
| 53 | + x -= 1; |
| 54 | + } else { |
| 55 | + direction = UP; |
| 56 | + offset += 1; |
| 57 | + y -= 1; |
| 58 | + } |
| 59 | + } else { |
| 60 | + if (y > 0 + offset) { |
| 61 | + y -= 1; |
| 62 | + } else { |
| 63 | + direction = RIGHT; |
| 64 | + x += 1; |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + if (result.length === matrix.length * matrix[0].length) { |
| 69 | + break; |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + return result; |
| 74 | +}; |
| 75 | + |
| 76 | +module.exports = { spiralOrder }; |
0 commit comments