牛客: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
}
相关推荐
立志成为coding大牛的菜鸟.1 小时前
力扣139-单词拆分(Java详细题解)
java·算法·leetcode
星夜孤帆2 小时前
LeetCode之数组/字符串
java·算法·leetcode
present12272 小时前
利用matlab bar函数绘制较为复杂的柱状图,并在图中进行适当标注
算法·matlab·数据分析·学习方法
蒙娜丽宁3 小时前
深入探讨Go语言中的切片与数组操作
开发语言·后端·golang·go
就这样很好8805 小时前
排序算法总结
java·算法·排序算法
weixin_486681145 小时前
C++系列-STL中find相关的算法
java·c++·算法
qq_172805595 小时前
GO HTTP库使用
http·golang·go
我是真爱学JAVA5 小时前
第四章 类和对象 课后训练(1)
java·开发语言·算法
Qiuner6 小时前
【机器学习】分类与回归——掌握两大核心算法的区别与应用
算法·机器学习·分类
oufoc6 小时前
第J1周:ResNet-50算法实战与解析
神经网络·算法·tensorflow