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

该题目来源于牛客网《剑指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
}
posted @ 2019-12-07 21:45  南方有嘉木1993  阅读(195)  评论(0编辑  收藏  举报