leetcode-Medium-22期-数组-Spiral Matrix

题目

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

  • Example 1
Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]

  • Example 2
Input:
[
 [1, 2, 3, 4],
 [5, 6, 7, 8],
 [9,10,11,12]
]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]

  • 思路
关键在于边界条件判断
可以理解为圆圈套圆圈
  • 解法
var spiralOrder = (matrix) => {
  let height = matrix.length
  let width = matrix[0] ? matrix[0].length : 0;
  let totalEle = height*width
  let res = []
  let i = 0;
  let count = 0
  while(count < totalEle){
    // 顶部元素
    if(count < totalEle){
      for(let j = i + 0; j < width - i; j++){
        res.push(matrix[i][j])
        count++
      }
    }
    if(count < totalEle){
         // 右边元素
      for( let j = i + 1; j <height - i ; j++){
        res.push(matrix[j][width - i - 1])
        count++
      }
    }
    if(count < totalEle){
          // 底部元素
      for( let j = width - 2 - i; j >=i; j--){ //j>=i不是j>=0
        res.push(matrix[height - i - 1][j])
        count++
      }
    }
    if(count < totalEle){
       //左边元素
      for( let j = height - 2 - i; j >i; j--){
        res.push(matrix[j][i])
        count++
      }
    }
 
    i++
  }
  return res
}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 掌柜的脸色总是难看,只有见到许久未还款的客户将铜板整整齐齐的摆在桌角,这才难得轻蔑的一笑。 "十九个铜板,一个...
    你永远猜不到的结局阅读 9,646评论 0 2
  • 前段时间我们听到一个聊得比较多的段子:北大清华毕业都买不起房,还买学区房做啥?这几年,大家炒的比较热的话题就有“学...
    张可以觉得可以阅读 1,462评论 0 0
  • ツギハギだらけの君との时间も 只是拼凑而出的与你在一起的时光 そろそろ终わりにしよう 也该差不多作个了断吧 この糸...
    打雷不怕阅读 890评论 0 0
  • 外面的风 涌上来,又退下去。 是冬风? 是春风? 莫名地, 吹乱了我的头绪!
    山间一清泉阅读 962评论 0 5