螺旋矩阵 leetcode59
初次尝试,从中心向外
func main() {n := 3fmt.Println(generateMatrix(n))
}
func generateMatrix(n int) [][]int {table := make([][]int, n)for i := 0; i < n; i++ {table[i] = make([]int, n)}var x, y = 0, 0 x = n / 2y = (n - 1) / 2fmt.Println("n:", n, " x:", x, " y:", y)table[x][y] = n * nvar char = 0 var char2 int var char3 int if n%2 == 1 {char3 = 1char2 = -1} else {char3 = -1char2 = 1}var c = 1for t, i := 1, n*n-1; i >= 0; { for e := 0; e < 2; e++ {tem := (c + 1) / 2 if char == 0 { for tem > 0 {y = y + char2if y == n+1 || y == -1 {return table}table[x][y] = ii--t++tem--}char2 = -char2char = 1} else { for tem > 0 {x = x + char3if x == n+1 || x == -1 {return table}table[x][y] = ii--t++if t == n*n {return table}tem--}char3 = -char3char = 0}c++}}return table
}
模拟方式
func generateMatrix(n int) [][]int {table := make([][]int, n)for i := 0; i < n; i++ {table[i] = make([]int, n)}i := 1 c := n - 1layerNums := 0 for ; c >= 0; c = c - 2 { x, y := layerNums, layerNums table[x][y] = ifor b := 0; b < c; b++ {table[x][y] = iy++i++}for b := 0; b < c; b++ {table[x][y] = ix++i++}for b := 0; b < c; b++ {table[x][y] = iy--i++}for b := 0; b < c; b++ {table[x][y] = ix--i++}layerNums++}return table
}