输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
示例 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]
golang
按照题目要求进行模拟,从左到右,从上到下,从右到左,从下往上的这样一个顺序
// 应该是采用模拟 右→下↓左←上↑的顺序
func spiralOrder(matrix [][]int) []int {
if len(matrix)==0{
return []int{}
}
rows := len(matrix)
cols := len(matrix[0])
var res []int
left, right, top, bottom := 0, cols-1, 0, rows-1 // 初始化
count, sum := 1, rows*cols
for count <= sum { // 循环的一个范围,数组的总个数
// 模拟向右→遍历
for i := left; i <= right; i++ {
res = append(res, matrix[top][i])
count++
}
top++ // 遍历下一层
if top > bottom {
break
}
// 模拟向下↓遍历
for i := top; i <= bottom; i++ {
res = append(res, matrix[i][right])
count++
}
right-- // 列数减一
if left > right {
break
}
// 模拟向左←遍历
for i := right; i >= left; i-- {
res = append(res, matrix[bottom][i])
count++
}
bottom-- // 往上走一行
if top > bottom {
break
}
// 模拟向上↑遍历
for i := bottom; i >= top; i-- {
res = append(res, matrix[i][left])
count++
}
left++ // 往内圈遍历
if left > right {
break
}
}
return res
}
原文:https://www.cnblogs.com/zmk-c/p/14759085.html