本文主要是介绍Leetcode 54 螺旋矩阵/59 螺旋矩阵II Golang,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
54 螺旋矩阵
func spiralOrder(matrix [][]int) []int {if len(matrix) == 0 {return []int{}}R, C := len(matrix), len(matrix[0])visited := make([][]int, R)for r := 0; r < R; r++ {visited[r] = make([]int, C)}N := R * Cres := make([]int, N)r, c, dr, dc := 0, 0, 0, 1for i := 0; i < N; i++ {res[i] = matrix[r][c]visited[r][c] = 1if visited[fix(dr+r, R) % R][fix(dc+c, C) % C] == 1 {dr, dc = dc, -dr}r, c = r + dr, c + dc}return res
}func fix(x, n int) int {if x < 0 {return x + n}return x
}
59 螺旋矩阵II
func generateMatrix(n int) [][]int {mtx := make([][]int, n)for r := 0; r < n; r++ {mtx[r] = make([]int, n)}r, c, dr, dc := 0, 0, 0, 1for i := 0; i < n*n; i++ {mtx[r][c] = i + 1if mtx[fix(r+dr, n) % n][fix(c+dc, n) % n] > 0 {dr, dc = dc, -dr}r, c = r + dr, c + dc}return mtx
}func fix(x, n int) int {if x < 0{return x + n}return x
}
这篇关于Leetcode 54 螺旋矩阵/59 螺旋矩阵II Golang的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!