Array - 59. Spiral Matrix II

72

59.Spiral Matrix II

Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

Example:

Input: 3
Output:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]

思路:

题目意思是给一个数n,让生成一个n*n的螺旋方阵,思路和54题很像,都是记录下需要访问的那一圈的四个顶点,作为遍历的依据。然后从1开始放数字就可以

代码:

go:

func generateMatrix(n int) [][]int {
    var res = make([][]int, n)
    for i := range res {
        res[i] = make([]int, n)
    }
    
    fillNumber(&res, 0, n-1, 0, n -1, 1)
    
    return res
}

func fillNumber(res *[][]int, top, bottom, left, right int, num int) {
    if top > bottom || left > right {
        return 
    }
    
    if top == bottom {
        for i := left; i <= right; i++ {
            (*res)[top][i] = num
            num++
        }
    } else if left == right {
        for i := top; i < bottom; i++ {
            (*res)[i][left] = num
            num++
        }
    } else {
        
        // 从左到右
        for i := left; i <= right - 1; i++ {
            (*res)[top][i] = num
            num++
        }
        
        // 从上到下
        for i := top; i <= bottom - 1; i++ {
            (*res)[i][right] = num
            num++
        }
        
        // 从左到右
        for i := right; i >= left + 1; i-- {
            (*res)[bottom][i] = num
            num++
        }
        
        // 从下到上
        for i := bottom; i >= top + 1; i-- {
            (*res)[i][left] = num
            num++
        }
    }
    
    fillNumber(res, top+1, bottom-1, left+1, right-1, num)
}