• 59.螺旋矩阵II
  • 54.螺旋矩阵
  • 剑指Offer 29.顺时针打印矩阵(同上)
/**
 * 螺旋矩阵
 */
function oMapMatrix(matrix) {
  const res = []
  const Y = matrix.length
  if (Y === 0) {
    return res
  }
  const X = matrix[0].length
 
  let x = 0
  let y = 0
  let dir = 'right'
  let border = [0, X - 1, Y - 1, 0] // 上右下左
 
  while (res.length < X * Y) {
    res.push(matrix[y][x])
    switch (dir) {
      case 'right':
        if (x === border[1]) {
          border[0]++
          y++
          dir = 'down'
        } else {
          x++
        }
        break
      case 'down':
        if (y === border[2]) {
          border[1]--
          x--
          dir = 'left'
        } else {
          y++
        }
        break
      case 'left':
        if (x === border[3]) {
          border[2]--
          y--
          dir = 'up'
        } else {
          x--
        }
        break
      case 'up':
        if (y === border[0]) {
          border[3]++
          x++
          dir = 'right'
        } else {
          y--
        }
    }
  }
 
  return res
}
 
/**
* Z 字矩阵
*/
function zMapMatrix(matrix) {
  const res = []
  const Y = matrix.length
  if (Y === 0) {
    return res
  }
  const X = matrix[0].length
 
  let x = 0
  let y = 0
  let isUp = false
 
  while (res.length < X * Y) {
    res.push(matrix[y][x])
    if (isUp) {
      if (x === X - 1) {
        y++
        isUp = false
      } else if (y === 0) {
        x++
        isUp = false
      } else {
        x++
        y--
      }
    } else {
      if (y === Y - 1) {
        x++
        isUp = true
      } else if (x === 0) {
        y++
        isUp = true
      } else {
        x--
        y++
      }
    }
  }
 
  return res
}
 
// ----------------- 测试 -------------------
 
const matrix3 = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
]
 
const matrix4 = [
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9, 10, 11, 12],
  [13, 14, 15, 16],
]
 
const matrix34 = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
  [10, 11, 12],
]
 
console.log(zMapMatrix(matrix3))