牛客: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
}
相关推荐
weixin_4588726112 分钟前
东华复试OJ二刷复盘2
算法
Charlie_lll13 分钟前
力扣解题-637. 二叉树的层平均值
算法·leetcode
爱淋雨的男人22 分钟前
自动驾驶感知相关算法
人工智能·算法·自动驾驶
wen__xvn34 分钟前
模拟题刷题3
java·数据结构·算法
滴滴答滴答答1 小时前
机考刷题之 6 LeetCode 169 多数元素
算法·leetcode·职场和发展
Neteen1 小时前
【数据结构-思维导图】第二章:线性表
数据结构·c++·算法
礼拜天没时间.1 小时前
力扣热题100实战 | 第25期:K个一组翻转链表——从两两交换到K路翻转的进阶之路
java·算法·leetcode·链表·递归·链表反转·k个一组翻转链表
Swift社区2 小时前
LeetCode 400 第 N 位数字
算法·leetcode·职场和发展
再难也得平2 小时前
力扣239. 滑动窗口最大值(Java解法)
算法·leetcode·职场和发展
摩尔曼斯克的海2 小时前
力扣面试题--双指针类
python·算法·leetcode