牛客:FZ12 牛牛的顺时针遍历

FZ12 牛牛的顺时针遍历

文章目录

题目描述

题解思路

通过一个变量来记录当前方向,遍历矩阵,每次遍历一条边,将该边的信息加入到结果中

题解代码

go 复制代码
func spiralOrder(matrix [][]int) []int {
	// write code here
	m, n := len(matrix), len(matrix[0])
	final := m * n
	res := make([]int, 0, final)
	// 0 >
	// 1 v
	// 2 <
	// 3 ^
	var direct int
	for i := 0; i < final; {
		switch direct {
		case 0:
            i += len(matrix[0])
			res = append(res, matrix[0]...)
			matrix = matrix[1:]
			direct = 1
		case 1:
			h := len(matrix)
            i += h
			v := len(matrix[0]) - 1
			for j := 0; j < h; j++ {
				res = append(res, matrix[j][v])
				matrix[j] = matrix[j][:v]
			}
            direct = 2
		case 2:
            v := len(matrix[0])
            i += v
			h := len(matrix) - 1
            for j := v - 1; j >= 0; j-- {
                res = append(res, matrix[h][j])
            }
            matrix = matrix[:h]
            direct = 3
		case 3:
			h := len(matrix)
            i += h
			for j := h - 1; j >= 0; j-- {
				res = append(res, matrix[j][0])
				matrix[j] = matrix[j][1:]
			}
            direct = 0
		}
	}
    return res
}
相关推荐
稚南城才子,乌衣巷风流43 分钟前
块状链表:数据结构详解与实现
数据结构·链表
Zachery Pole1 小时前
CCF-CSP备战NO.7【队列】
算法
闪电悠米1 小时前
力扣hot100-48.旋转图像-转置翻转详解
算法·leetcode·职场和发展
满天星83035771 小时前
【算法】最长递增子序列(三种解法)
算法
啦啦啦啦啦zzzz2 小时前
算法:贪心算法
c++·算法·leetcode·贪心算法
日拱一卒——功不唐捐3 小时前
红黑树删除(C语言)
c语言·数据结构
清泓y4 小时前
RAG 技术
算法·ai
不如语冰4 小时前
AI大模型入门-Python进阶-上下文管理与with语句
开发语言·数据结构·数据库·人工智能·pytorch·redis·python
阿慧今天瘦了嘛4 小时前
计算机组成原理概述:从硬件到软件的桥梁
计算机网络·算法
光头闪亮亮4 小时前
Fyne ( go跨平台GUI )项目实战-scanner摄像头扫码组件开发技术详解
android·go