59. 螺旋矩阵 II

59. 螺旋矩阵 II #

题目地址 #

解题思路 #

可以参考 https://leetcode.cn/problems/spiral-matrix-ii/solutions/12594/spiral-matrix-ii-mo-ni-fa-she-ding-bian-jie-qing-x/

具体实现 #

package main

import "fmt"

func main() {
	n := 3
	fmt.Println(generateMatrix(n))
}

func generateMatrix(n int) [][]int {
	ret := make([][]int, n)
	startX, startY := 0, 0
	count := 1
	offset := 1
	loop := n / 2

	for i := 0; i < n; i++ {
		ret[i] = make([]int, n)
	}

	for loop > 0 {
		i, j := startX, startY

		for j = startY; j < n-offset; j++ {
			ret[startX][j] = count
			count++
		}
		for i = startX; i < n-offset; i++ {
			ret[i][j] = count
			count++
		}

		for ; j > startY; j-- {
			ret[i][j] = count
			count++
		}

		for ; i > startX; i-- {
			ret[i][j] = count
			count++
		}

		startX++
		startY++
		offset++
		loop--
	}

	if n%2 == 1 {
		ret[n/2][n/2] = n * n
	}

	return ret
}

参考 #