用 Go 剑指 Offer 29. 顺时针打印矩阵
给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
示例 2:
输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]
提示:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/spiral-matrix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
消消乐法:顺时针走,读取一行就删一行
func spiralOrder(matrix [][]int) []int { if len(matrix) == 0 || len(matrix[0]) == 0{ return []int{} } res := make([]int, 0) up, left, down, right := 0, 0, len(matrix)-1, len(matrix[0])-1 for { for i := left; i <= right; i++ { res = append(res, matrix[up][i]) } up++ if up > down { break } for i := up; i <= down; i++ { res = append(res, matrix[i][right]) } right-- if right < left { break } for i := right; i >= left; i-- { res = append(res, matrix[down][i]) } down-- if down < up { break } for i := down; i >= up; i-- { res = append(res, matrix[i][left]) } left++ if left > right { break } } return res }
hello my world
本文来自博客园,作者:slowlydance2me,转载请注明原文链接:https://www.cnblogs.com/slowlydance2me/p/17296783.html