zoukankan      html  css  js  c++  java
  • 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
    }
    
  • 相关阅读:
    【LeetCode】543. 二叉树的直径
    红色的眼睛黑色的心
    WinForm
    Windows地址栏的妙用
    C#
    WPF
    配置Notepad++万能调试
    盗取连接你wifi的人的qq
    Windows去除开始菜单图标背景
    解决Windows下文件无法删除的问题
  • 原文地址:https://www.cnblogs.com/dubinyang/p/12099402.html
Copyright © 2011-2022 走看看