牛客: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
}
相关推荐
爱是小小的癌1 小时前
Java-数据结构-优先级队列(堆)
java·前端·数据结构
sjsjs111 小时前
【数据结构-字典树】力扣14. 最长公共前缀
数据结构·leetcode
python算法(魔法师版)1 小时前
基于机器学习鉴别中药材的方法
深度学习·线性代数·算法·机器学习·支持向量机·数据挖掘·动态规划
JNU freshman2 小时前
力扣第435场周赛讲解
算法·leetcode·蓝桥杯
眼镜哥(with glasses)2 小时前
蓝桥杯python基础算法(2-2)——基础算法(B)——模拟(上)
算法
赵鑫亿4 小时前
7.DP算法
算法·dp
iqay4 小时前
【C语言】填空题/程序填空题1
c语言·开发语言·数据结构·c++·算法·c#
还有糕手4 小时前
算法【有依赖的背包】
算法·动态规划
pursuit_csdn5 小时前
力扣 347. 前 K 个高频元素
算法·leetcode
wen__xvn5 小时前
每日一题洛谷B3865 [GESP202309 二级] 小杨的 X 字矩阵c++
c++·算法·矩阵