Skip to content

Latest commit

 

History

History
39 lines (39 loc) · 849 Bytes

59螺旋矩阵II.md

File metadata and controls

39 lines (39 loc) · 849 Bytes

模拟过程

func generateMatrix(n int) [][]int {
    res := make([][]int, n)
    for i := 0; i < n; i++ {
        res[i] = make([]int, n)
    }
    left, right := 0, n - 1
    top, bottom := 0, n - 1
    count := 1
    for count <= n * n {
        // 从左到右
        for x := left; x <= right; x++ {
            res[top][x] = count
            count++
        }
        top++
        // 从上到下
        for y := top; y <= bottom; y++ {
            res[y][right] = count
            count++
        }
        right--
        // 从右到左
        for x := right; x >= left; x-- {
            res[bottom][x] = count
            count++
        }
        bottom--
        // 从下到上
        for y := bottom; y >= top; y-- {
            res[y][left] = count
            count++
        }
        left++
    }
    return res
}