SoFunction
Updated on 2025-03-05

Example of method of golang printing matrix clockwise

Question description

Enter a matrix and print each number in clockwise order from the outside to the inside. For example, if you enter the following 4 X 4 matrix: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Then print the numbers 1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10 in turn.

package main

import "fmt"

func main() {
  //s := [][]int{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}
  //s := [][]int{{1}, {2}, {3}, {4}}
  //s := [][]int{{1, 2, 3, 4}, {5, 6, 7, 8}}
  s := [][]int{{1, 2}, {5, 6}, {9, 10}, {13, 14}}

  printMatrix(s)
}
func printMatrix(s [][]int) {
  if s == nil {
    ("Slice is empty, cannot be printed")
  }
  bex, bey := 0, 0
  hang := len(s) - 1
  lie := len(s[0]) - 1
  if hang == 0 {
    for _, v := range s[0] {
      (v)
    }
    return
  }
  if lie == 0 {
    for _, v := range s {
      (v[0])
    }
    return
  }
  for bex <= hang && bey <= lie {
    ax, ay := bex, bey
    for ay < lie {
      (s[ax][ay])
      ay++
    }
    for ax < hang {
      (s[ax][ay])
      ax++
    }
    for ay > bey {
      (s[ax][ay])
      ay--
    }
    for ax > bex {
      (s[ax][ay])
      ax--
    }
    bex++
    bey++
    hang--
    lie--
  }
}

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.