【问题标题】:Why doesnt it show the path?为什么不显示路径?
【发布时间】:2023-01-18 05:16:23
【问题描述】:

我试图显示此 Dijkstra 算法采用的路径,但是,一旦程序结束,它应该显示采用的路径以及已采用的步骤数。但它只显示了 end_pos 和 1 步我已经多次查看代码但也许我太累了以至于无法识别错误或者我只是愚蠢......任何人有任何想法吗?

# imports go here


class DijkstraPathfinder:
    @staticmethod
    def find_path():
        def _get_start_and_end_pos():
            start_pos, end_pos = None, None
            for row in grid:
                for square in row:
                    if square.state == SquareState.START:
                        start_pos = square.row, square.col
                    elif square.state == SquareState.END:
                        end_pos = square.row, square.col

            return start_pos, end_pos

        def _get_valid_neighbours(r: int, c: int):
            """
            Find valid neighbours for a square:
            valid means it's not a wall, has not been visited
            :param r: row
            :param c: column
            :return: valid neighbours
            :rtype: list()
            """

            up_neighbour = (r, c + 1)
            down_neighbour = (r, c - 1)
            left_neighbour = (r - 1, c)
            right_neighbour = (r + 1, c)

            neighbours = [up_neighbour, down_neighbour, left_neighbour, right_neighbour]
            v_neighbours = list()

            for neighbour in neighbours:
                r, c = neighbour
                if r in range(settings.ROWS) and c in range(settings.ROWS):
                    if grid[r][c].state not in [SquareState.VISITED, SquareState.WALL, SquareState.START]:
                        v_neighbours.append(neighbour)

            return v_neighbours

        def _reconstruct_path():
            path = [end_pos]
            current = end_pos

            while prev[current]:
                path.append(prev[current])
                current = prev[current]
                # print(u)

            path.reverse()
            return path

        WINDOW = pygame.display.set_mode((800, 800))
        grid = Creator.get_grid()

        start_pos, end_pos = _get_start_and_end_pos()

        print()
        print(f'Starting position: {start_pos}')
        print(f'Ending position: {end_pos}')
        print()

        dist = {}
        prev = {}
        q = list()

        finished = False

        while not finished:

            for row in grid:
                for square in row:
                    pos = square.get_pos()

                    dist[square.get_pos()] = float("inf")
                    prev[square.get_pos()] = None
                    if square.state in [SquareState.EMPTY, SquareState.START, SquareState.END]:
                        q.append(pos)

            dist[start_pos] = 0

            while q:
                u = min(q, key=dist.__getitem__)
                q.remove(u)

                for v in _get_valid_neighbours(*u):
                    alt = dist[u] + 1

                    if alt < dist[v]:
                        dist[v] = alt
                        prev[v] = u

                        vr, vc = v
                        grid[vr][vc].change_state(SquareState.VISITED)

                    if v == end_pos:
                        q = list()
                        break

                picasso.draw(WINDOW, grid)
                for event in pygame.event.get():
                    if event.type == pygame.QUIT:
                        finished = True
                        q = list()
                        break

            path = _reconstruct_path()

            for square in path:
                row, col = square
                grid[row][col].change_state(SquareState.PATH)
                picasso.draw(WINDOW, grid)
                for event in pygame.event.get():
                    if event.type == pygame.QUIT:
                        finished = True
                        break

        print(f'Path found, took {len(path)} moves')
        print(f'Moves: {path}')
        print()

        pygame.quit()


if __name__ == '__main__':
    DijkstraPathfinder.find_path()

我试图改变这一点,尤其是最后的印刷品,但它似乎仍然在做同样的事情,它只显示“找到路径,采取了 1 步”,然后在它下面显示“移动:end_pos”,其中 end_pos 在哪里你已经提出了最后一点。

【问题讨论】:

    标签: python algorithm dijkstra


    【解决方案1】:

    在您迭代邻居的实现中:

    for v in _get_valid_neighbours(*u)
    

    您没有向q 附加任何内容,因此迭代就此停止。结果,在_reconstruct_path()中,终点没有prev节点,你得到的路径长度为1。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-09
      • 2017-03-04
      • 2019-09-12
      • 1970-01-01
      • 2011-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多