Go语言实现:【剑指offer】顺时针打印矩阵

本文介绍了一种使用Go语言实现的算法,该算法能够按顺时针方向从外向里打印矩阵中的每一个数字。通过定义边界和循环遍历的方式,实现了对矩阵元素的有效访问。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

该题目来源于牛客网《剑指offer》专题。

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。

例如,如果输入如下4 X 4矩阵:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16,则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10。

Go语言实现:

func printMatrix(matrix [][]int) []int {
   result := []int{}
   row := len(matrix)
   if row == 0 {
      return result
   }
   column := len(matrix[0])
   if column == 0 {
      return result
   }
   //定义下标变量
   top := 0
   bottom := row - 1
   left := 0
   right := column - 1
   for left <= right && top <= bottom {
      //从左往右,行数为top,列数从left开始,+1直到right
      for i := left; i <= right; i++ {
         result = append(result, matrix[top][i])
      }
      //从上往下,行数从top+1开始,+1直到bottom,列数为right
      for i := top + 1; i <= bottom; i++ {
         result = append(result, matrix[i][right])
      }
      //row不重复,从右往左,行数为bottom,列数从right-1开始,-1直到left
      if top != bottom {
         for i := right - 1; i >= left; i-- {
            result = append(result, matrix[bottom][i])
         }
      }
      //column不重复,从下往上,行数从bottom-1开始,-1直到top-1,所以没有等号
      if left != right {
         for i := bottom - 1; i > top; i-- {
            result = append(result, matrix[i][left])
         }
      }
      //一圈结束
      left++
      right--
      top++
      bottom--
   }
   return result
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值