微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

dfs 中的元组索引超出范围

如何解决dfs 中的元组索引超出范围

这是我的代码

class solution:
    lot = [[1,0],[1,9,1]]   
    def move(lot):
        if lot is None:
            return -1
        if (len(lot) <= 0 or len(lot[0]) <= 0):
            return -1
        q = []
        visited = [len(lot)],[len(lot[0])]
        direction= [(0,1),(0,-1),(1,0),(-1,0)]
        q.append((0,0))
        result = 0
        
        while (len(q) > 0):
            size = len(q)
            for i in range(size):
                node= q.pop(0)
                x = node[0]
                y = node[1]
                visited[x][y]= True
                if(lot[x][y] == 9):
                    return result
                for dir in direction:
                    nx = x+ dir[0]
                    ny = y + dir[1]
                    r= len(lot[nx])
                    
                    
                    if (nx < 0 or nx >= len(lot) or ny < 0 or ny > r or lot[nx][ny] == 0 or visited[nx][ny] == True):
                        continue
                    q.append((nx,ny))
                
            result += result
        return result
    print(move(lot))

它产生以下错误

File "prog.py",line 29,in move
    if (nx < 0 or nx >= len(lot) or ny < 0 or ny > r or lot[nx][ny] == 0 or visited[nx][ny] == True):
IndexError: tuple index out of range

解决方法

您的错误是由于您的 visited 变量造成的。您正在尝试访问不存在的 visited[nx][ny]。 另外,您的 DFS 算法不正确。有关如何正确实施 DFS,请参阅 here

你的函数应该是这样的:

def move(lot):
    if lot is None:
        return -1
    if (len(lot) <= 0 or len(lot[0]) <= 0):
        return -1
    
    q = []
    visited = set()
    q.append((0,0))
    result = 0
    
    while len(q)>0:
        x,y = q.pop(0)
        if(lot[x][y]==9):
            return result
        if (x,y) in visited:
            continue
        visited.add((x,y))
        for d in [(0,1),(0,-1),(1,0),(-1,0)]:
            nx = x + d[0]
            ny = y + d[1]
            if (nx<0 or nx>=len(lot) or ny<0 or ny>len(lot[0]) or lot[nx][ny]==0 or (nx,ny) in visited):
                continue
            q.append((nx,ny))       
            result += 1
    return result

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。