Search code examples
pythonsearchmatrixbreadth-first-searchgrid-search

TypeError while running bfs algo code in Python


So, here is the code I am running and it's giving me a TypeError. I am trying to traverse a 2d array and then returning the path from starting point to the target point.

I applied Breadth-first search for the path traversing but seems like something is wrong with the algorithm.

class Grid:
    def __init__(self, str1):
        self.maze = str1.splitlines()

    def get_start_cordinates(self):
        rr = 0
        cc = 0
        return rr, cc

    def main(self, r, c):
        queue = []
        visited = {}
        visited[(r, c)] = (-1, -1)
        queue.append((r, c))
        while len(queue) > 0:
            r, c = queue.pop(0)

            if r == 4 and c == 2:
                path_actual = []
                while r != -1:
                    path_actual.append((r, c))
                    r, c = visited[(r, c)]
                path_actual.reverse()
                return path_actual

            # avoid repetition of code: make a loop
            for dx, dy in ((-1, 0), (0, -1), (1, 0), (0, 1), (1, 1), (1, -1), (-1, 1), (-1, -1)):
                new_r = r + dy
                new_c = c + dx
                if (0 <= new_r < len(self.maze) and
                        0 <= new_c < len(self.maze[0]) and
                        not (new_r, new_c) in visited):
                    visited[(new_r, new_c)] = (r, c)
                    queue.append((new_r, new_c))


maze = Grid("""1 12 2 0 0
2 11 1 11 0
3 2 -1 9 0""")

path = Grid.main(*Grid.get_start_cordinates())
print(path)

This is the error I am getting:

path = Grid.main(*Grid.get_start_cordinates())

TypeError: get_start_cordinates() missing 1 required positional argument: 'self'


Solution

  • path = maze.main(*maze.get_start_cordinates())
    

    use the object you created not the class.