## Array - 59. Spiral Matrix II

Updated on with 0 views and 0 comments

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 ]
]

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)
}
``````