题目介绍
解题代码
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
}
作者:代码随想录
链接:https://leetcode.cn/problems/spiral-matrix-ii/solutions/1706277/by-carlsun-2-72fa/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
注意事项及问题
这题花费了两个小时进行调试,主要是因为不知道当时自己的输出为什么会出错,下面贴出我原本的代码,今后可以引以为鉴
package main
import "fmt"
func generateMatrix(n int) [][]int {
left,right,top,bottom,total,count,i,j := 0,n-1,0,n-1,n*n,1,0,0
nums := make([][]int,n)
for z:=0;z<n;z++{
nums[z] = make([]int,n)
}
for count < total{
for ;j < right; j++{
fmt.Println(count)
nums[top][j] = count
count ++
}
top ++
for ;i < bottom;i++{
fmt.Println(count)
nums[i][j] = count
count ++
}
right --
for ;j > left;j--{
fmt.Println(count)
nums[i][j] = count
count ++
}
bottom --
for ;i > top;i--{
fmt.Println(count)
nums[i][j] = count
count ++
}
fmt.Println(count)
left ++
}
return nums
}
func main() {
b := generateMatrix(3)
fmt.Println(b)
}
这里面主要的错误就是因为每次遍历一行或者一列后,会对四个标志(left等)进行修改,这就导致后面的循环会出现越界或者少遍历的情况,所以遇到这种需要修改坐标标志的题目时,首先应该观察修改的标志在循环中是否能够继续使用,或者按照标准答案(代码随想录佬)方式,当有修改坐标标志的情况下,每次都利用一个变量对其进行取值,这样可以避免以上情况。