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

数组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 上重要算法,以及一些经典算法
  • 此处答案仅为参考,不一定是最优解,欢迎感兴趣的读者在评论区提供更优解
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

昕光xg

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值