算法-程序输入为矩阵如何遍历?

本文分享了在LeetCode中解决1091题的经验,探讨了如何处理矩阵输入并遍历其相邻节点。通过设置横纵坐标变化值数组x和y,有效地解决了在矩阵中进行四向或八向遍历的问题,从而克服了对矩阵题型的困扰。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

力扣1091 https://leetcode-cn.com/problems/shortest-path-in-binary-matrix/

python3

启发:过去一两个月的笔试过程中,最最怕遇到的就是输入为矩阵的题型,一直不知道该怎么遍历某以位置的相邻8个节点。今天在leetcode刷题终于遇到了,才发现还是有一个比较正规的遍历方法。设置两个数组x和y,分别代表当前位置到相邻位置的横纵坐标变化值。如果题目限制只能是上下左右,这两个数组的长度就都是4;否则默认为8。

收获很小,但也很大,至少解决了对一种题型的恐惧感。

class Solution:
    def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
        n = len(grid)
        if n==1:
            return 1
        if not grid[0][0]==0 or not grid[n-1][n-1]==0:
            return -1
        visited = [[0]*n for _ in range(n)]
        stack = [[0,0]]
        visited[0][0] = 1
        step = 1
        x=[-1,-1,-1,0,0,1,1,1]
        y=[-1,0,1,-1,1,-1,0,1]
        tmp = []
        while len(stack):#第i+1步能走的格子
            cur_x,cur_y =stack.pop()
            step = visited[cur_x][cur_y]
            step += 1 
            for k in range(8):
                next_x = cur_x+x[k]
                next_y = cur_y+y[k]
                if next_x==n-1 and next_y==n-1:
                    return step
                if 0<=next_x<=n-1 and 0<=next_y<=n-1 and grid[next_x][next_y]==0 and visited[next_x][next_y]==0:
                    tmp.append([next_x,next_y])
                    visited[next_x][next_y] = step
            if len(stack) ==0:
                stack = tmp.copy()
                tmp = []
        return -1

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值