前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Array - 54. Spiral Matrix

Array - 54. Spiral Matrix

作者头像
ppxai
发布2020-09-23 17:46:59
2690
发布2020-09-23 17:46:59
举报
文章被收录于专栏:皮皮星球皮皮星球

54.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:

代码语言:javascript
复制
Input:
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]

Example 2:

代码语言:javascript
复制
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]

思路:

题目意思是螺旋打印矩阵,思路就是从左往右,从上往下,再从右往左,最后从下往上打印,然后更新边界,递归或者迭代就可以。

第一次在面试官面前直播代码,紧张的不行,以后得稳着点,瞬间脑子都不转了. ?

代码:

go:

代码语言:javascript
复制
func spiralOrder(matrix [][]int) []int {
    var  res []int
    if matrix == nil || len(matrix) == 0 {
        return res
    }
    printGrid(matrix, 0, len(matrix) -1, 0, len(matrix[0]) - 1, &res)
    return res
}

func printGrid(grid [][]int, top, bottom, left, right int, res *[]int) {
    // 递归出口
    if top > bottom || left > right {
        return 
    }   
    
    if top == bottom {  // 1. 只有一列的情况
      for i := left; i <= right; i++ {
        *res = append(*res, grid[top][i])
      }
    } else if left == right {  // 2. 只有一行的情况
      for i := top; i <= bottom; i++ {
        *res = append(*res, grid[i][left])
      }
    } else {  // 3.正常绕圈打印
      // 从左往右打印
      for i := left; i <= right - 1; i++ {
          *res = append(*res, grid[top][i])
      }
        
      // 从上往下打印
      for i := top; i <= bottom - 1; i++ {
          *res = append(*res, grid[i][right])
      }

      // 从右往左打印
      for i := right; i >= left + 1; i-- {
          *res = append(*res, grid[bottom][i])
      }
        
      // 从下往上打印
      for i := bottom; i >= top + 1; i-- {
          *res = append(*res, grid[i][left])
      }
    }
    
    printGrid(grid, top+1, bottom-1, left+1, right-1, res)
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020年05月17日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
云直播
云直播(Cloud Streaming Services,CSS)为您提供极速、稳定、专业的云端直播处理服务,根据业务的不同直播场景需求,云直播提供了标准直播、快直播、云导播台三种服务,分别针对大规模实时观看、超低延时直播、便捷云端导播的场景,配合腾讯云视立方·直播 SDK,为您提供一站式的音视频直播解决方案。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档