Search code examples
pythonindexingtuplesrangedepth-first-search

tuple index out of range in dfs


This is my code:

class solution:
    lot = [[1,0,0], [1,0,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))

It generates the following error:

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

Solution

  • Your error is because of your visited variable. You're trying to access visited[nx][ny] which doesn't exist. Separately, your DFS algorithm is incorrect. See here for how to implement DFS correctly.

    Your function should be like this:

    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