Golang | Leetcode Golang题解之第59题螺旋矩阵II-题解:

时间:2024-05-01 19:01:30
func generateMatrix(n int) [][]int {
    matrix := make([][]int, n)
    for i := range matrix {
        matrix[i] = make([]int, n)
    }
    num := 1
    left, right, top, bottom := 0, n-1, 0, n-1
    for left <= right && top <= bottom {
        for column := left; column <= right; column++ {
            matrix[top][column] = num
            num++
        }
        for row := top + 1; row <= bottom; row++ {
            matrix[row][right] = num
            num++
        }
        if left < right && top < bottom {
            for column := right - 1; column > left; column-- {
                matrix[bottom][column] = num
                num++
            }
            for row := bottom; row > top; row-- {
                matrix[row][left] = num
                num++
            }
        }
        left++
        right--
        top++
        bottom--
    }
    return matrix
}