牛客: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
}
相关推荐
wuxiguala9 分钟前
【文件系统—散列结构文件】
linux·算法
keepDXRcuriosity24 分钟前
深入探索快速排序算法:原理与 C 语言实现
c语言·算法·排序算法
flying_13141 小时前
面试常问系列(一)-神经网络参数初始化-之-softmax
深度学习·神经网络·算法·机器学习·面试
蒟蒻小袁2 小时前
力扣面试150题-- 翻转二叉树
算法·leetcode·面试
养一只Trapped_beast2 小时前
【LeetCode】删除排序数组中的重复项 II
算法·leetcode·职场和发展
矢鱼2 小时前
单调栈所有模版(2)
算法
轮到我狗叫了2 小时前
力扣智慧思想小题,目录力扣.跳跃游戏(思想很重要)力扣.跳跃游戏II(还是思想)力扣.分发糖果力扣151.反转字符串中的单词力扣.轮转数组
数据结构·算法·leetcode
zxctsclrjjjcph2 小时前
【递归、搜索和回溯】递归、搜索和回溯介绍及递归类算法例题
开发语言·c++·算法·力扣
朱剑君3 小时前
排序算法——堆排序
算法·排序算法
10000hours3 小时前
【SGL】Scatter-Gather List内存传输技术
linux·数据结构·网络协议·list·存储·sgl