进军大厂-从零开始算法基础(5)螺旋矩阵--力扣 go

题目介绍


解题代码

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等)进行修改,这就导致后面的循环会出现越界或者少遍历的情况,所以遇到这种需要修改坐标标志的题目时,首先应该观察修改的标志在循环中是否能够继续使用,或者按照标准答案(代码随想录佬)方式,当有修改坐标标志的情况下,每次都利用一个变量对其进行取值,这样可以避免以上情况。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值