数组05--顺时针打印矩阵-jz19

题目概述

  • 算法说明
    输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下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.
  • 测试用例
    输入:
    [[1,2],[3,4]]
    输出:
    [1,2,4,3]

解析&参考答案

  • 解析
    循环一圈一圈地打印,只要left<=right且bottom<=top 就会循环打印一圈,打印顺序为top、right、bottom、left,每次转方向时候都需要确定最大或最小临界值。
  • 参考答案
vim jz19.go
package main

import (
"fmt"
)

func printMatrix(matrix [][]int) []int {
var ret []int
row := len(matrix)
col := len(matrix[0])
left, right, top, bottom := 0, col-1, row-1, 0
for left <= right && bottom <= top {
// print top line
for c := left; c <= right; c++ {
ret = append(ret, matrix[bottom][c])
}
// print right line
for r := bottom + 1; r <= top; r++ {
ret = append(ret, matrix[r][right])
}
// print bottom line
if bottom != top {
for c := right - 1; c >= left; c-- {
ret = append(ret, matrix[top][c])
}
}
// print left line
if left != right {
for r := top - 1; r >= bottom+1; r-- {
ret = append(ret, matrix[r][left])
}
}
left++
bottom++
right--
top--
}
return ret
}

func main() {
array := [][]int{{1, 2}, {3, 4}}
result := printMatrix(array)
fmt.Println(result)
}

注意事项

  1. to add

说明

  1. 当前使用 go1.15.8
  2. 参考​​牛客网--剑指offer​​ 标题中jzn(n为具体数字)代表牛客网剑指offer系列第n号题目,例如 jz01 代表牛客网剑指offer中01号题目。

注意!!!

  • 笔者最近在学习 golang,因此趁机通过数据结构和算法来进一步熟悉下go语言
  • 当前算法主要来源于剑指 offer,后续会进一步补充 LeetCode 上重要算法,以及一些经典算法
  • 此处答案仅为参考,不一定是最优解,欢迎感兴趣的读者在评论区提供更优解