牛客: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
}
相关推荐
earthzhang202128 分钟前
【1007】计算(a+b)×c的值
c语言·开发语言·数据结构·算法·青少年编程
2301_803554522 小时前
C++联合体(Union)详解:与结构体的区别、联系与深度解析
java·c++·算法
sali-tec3 小时前
C# 基于halcon的视觉工作流-章42-手动识别文本
开发语言·人工智能·算法·计算机视觉·c#·ocr
SandySY3 小时前
品三国谈人性
算法·架构
小欣加油4 小时前
leetcode 62 不同路径
c++·算法·leetcode·职场和发展
夏鹏今天学习了吗4 小时前
【LeetCode热题100(38/100)】翻转二叉树
算法·leetcode·职场和发展
夏鹏今天学习了吗4 小时前
【LeetCode热题100(36/100)】二叉树的中序遍历
算法·leetcode·职场和发展
DTS小夏4 小时前
算法社Python基础入门面试题库(新手版·含答案)
python·算法·面试
Mr.Ja4 小时前
【LeetCode热题100】No.11——盛最多水的容器
算法·leetcode·贪心算法·盛水最多的容器
冷徹 .4 小时前
2024ICPC区域赛香港站
数据结构·c++·算法