代码拉取完成,页面将自动刷新
package main
import "fmt"
var Direct = [][]int{{0,1},{1,0},{0,-1},{-1,0}}
func spiralOrder(matrix [][]int) []int {
// m行n列
m , n , x, y := len(matrix) , len(matrix[0]) , 0 ,0
currM , currN ,mSide , nSide , d := m , n , 0 , 0, 0
res := []int{matrix[0][0]}
for len(res) < m * n {
// 四个方向的循环
idx := d % 4
dy , dx := Direct[idx][0] , Direct[idx][1]
y , x = y + dy , x + dx
// 控制转转向
if y < mSide || x < nSide || y >= currM || x >= currN {
d ++
y ,x = y -dy , x - dx
continue
}
// 控制迭代
if idx == 3 && y == mSide + 1 {
res = append(res, matrix[y][x])
mSide ++ ; nSide ++ ; currM -- ; currN --
continue
}
res = append(res , matrix[y][x])
}
return res
}
func main() {
fmt.Println(spiralOrder([][]int{{1,2,3},{4,5,6},{7,8,9}}))
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。