LeetCode-54. Spiral Matrix

问题描述

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

Example :

img

1
2
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]

Constraints:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 10
  • -100 <= matrix[i][j] <= 100

解答

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/*
* @Description: 54. Spiral Matrix
* @Author: libk
* @Github: https://github.com/libk
*/
/**
* @param {number[][]} matrix
* @return {number[]}
*/
const spiralOrder = function (matrix) {
if (!matrix || !matrix.length || !matrix[0].length) {
return []
}

const rowLen = matrix.length - 1
const colLen = matrix[0].length - 1
let top = 0
let left = 0
let bottom = rowLen
let right = colLen

const path = []

while (top <= bottom && left <= right) {
for (let col = left; col <= right; col++) {
path.push(matrix[top][col])
}
for (let row = top + 1; row <= bottom; row++) {
path.push(matrix[row][right])
}
// top===bottom或left===right时,说明只剩最后一行或者一列
if (top < bottom && left < right) {
for (let col = right - 1; col >= left; col--) {
path.push(matrix[bottom][col])
}
for (let row = bottom - 1; row > top; row--) {
path.push(matrix[row][left])
}
}
top++
left++
bottom--
right--
}
return path
}