59. 螺旋矩阵 II

59. 螺旋矩阵 II

mid

给你一个正整数 n ,生成一个包含 1n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix

1 <= n <= 20

https://markdown-1303167219.cos.ap-shanghai.myqcloud.com/image-20220226222442141.png

模拟

就恩写;注意边界条件

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
func generateMatrix(n int) [][]int {
	if n == 1 {
		return [][]int{{1}}
	}
	res := make([][]int, n)
	for i := 0; i < n; i++ {
		res[i] = make([]int, n)
	}
	count := 1
	for layer := 0; layer <= n-2; layer++ {
		// 顺时针填空 左闭右开 中心特例
		if layer == n-layer-1 {
			// 中心
			res[layer][layer] = n * n
			break
		}
		// l2r
		for col := layer; col < n-layer-1; col++ {
			res[layer][col] = count
			count++
		}
		// u2d
		for row := layer; row < n-layer-1; row++ {
			res[row][n-layer-1] = count
			count++
		}
		// r2l
		for col := n - layer - 1; col > layer; col-- {
			res[n-layer-1][col] = count
			count++
		}
		// d2u
		for row := n - layer - 1; row > layer; row-- {
			res[row][layer] = count
			count++
		}
	}
	return res
}

更好懂的模拟

螺旋矩阵
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
func generateMatrix(n int) [][]int {
    top, bottom := 0, n-1
    left, right := 0, n-1
    num := 1
    tar := n * n
    matrix := make([][]int, n)
    for i := 0; i < n; i++ {
        matrix[i] = make([]int, n)
    }
    for num <= tar {
        for i := left; i <= right; i++ {
            matrix[top][i] = num
            num++
        }
        top++
        for i := top; i <= bottom; i++ {
            matrix[i][right] = num
            num++
        }
        right--
        for i := right; i >= left; i-- {
            matrix[bottom][i] = num
            num++
        }
        bottom--
        for i := bottom; i >= top; i-- {
            matrix[i][left] = num
            num++
        }
        left++
    }
    return matrix
}