矩阵算法之螺旋矩阵(spiral matrix)

  • A+
所属分类:typescript 算法
/*
螺旋矩阵
input = [
          [1, 2, 3, 4]
          [5, 6, 7, 8]
          [9, 10, 11, 12]
          [13, 14, 15, 16]
        ]

output = [ 1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7, 11, 10 ]
 */

const matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]

function solution(matrix: Array<Array<number>>): Array<number> {
  let len = matrix.length
  let res = []
  if (len === 0) return res

  let rowStart = 0
  let rowEnd = len - 1
  let colStart = 0
  let colEnd = matrix[0].length - 1

  while (rowStart <= rowEnd && colStart <= colEnd) {
    for (let i = colStart; i <= colEnd; i++) {
      res.push(matrix[rowStart][i])
    }
    rowStart++
    for (let i = rowStart; i <= rowEnd; i++) {
      res.push(matrix[i][colEnd])
    }
    colEnd--
    if (rowStart <= rowEnd) {
        for (let i = colEnd; i >= colStart; i--) {
            res.push(matrix[rowEnd][i])
        }
    }
    rowEnd--
    if (colStart <= colEnd) {
        for (let i = rowEnd; i >= rowStart; i--) {
            res.push(matrix[i][colStart])
        }
    }
    colStart++
  }
  return res
}

console.log(solution(matrix))

weinxin
我的微信
欢迎来撩!!
admin

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: