首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >广度优先搜索优化

广度优先搜索优化
EN

Stack Overflow用户
提问于 2018-10-17 19:05:27
回答 1查看 116关注 0票数 0

我最近一直在编写一些介绍性的图论,并遇到了以下问题说明:

给定一个2D矩阵作为输入,表示一个迷宫(其中'E‘是矩阵的开始,' S’是结束),找出从E到S的最短路径的长度,迷宫中的墙壁用'#‘表示,而可访问的空间用'.’表示。它也是一个给定的,矩阵的外部边缘被墙壁覆盖。如果不存在从E到S的路径,return -1

由于图形没有加权,所以我尝试使用deque实现BFS算法。然而,当迷宫开始达到500×500左右时,执行时间达到10s,而当我试图提高到1000x1000时,情况显然要糟糕得多。

,这是我的代码:

代码语言:javascript
复制
from collections import deque

def shortest_path_1(maze):
    wall, clear, endchar, startchar = '#', '.', 'S', 'E'
    height = len(maze)
    width = len(maze[0])

    def find_start(grid):
        for y in range(1, height-1):
            for x in range(1, width-1):
                if grid[y][x] == startchar:
                    return tuple([x, y])

    start = find_start(maze)

    queue = deque([[start]])

    seen = {start}
    while queue:
        path = queue.popleft()
        x, y = path[-1]
        if maze[y][x] == endchar:
            return len(path)-1
        for (x2, y2) in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)):
            if 0 < x2 < width-1 and 0 < y2 < height-1 and maze[y2][x2] != wall and (x2, y2) not in seen:
                queue.append(path + [(x2, y2)])
                seen.add((x2, y2))

    return -1

到目前为止,我在网站上找到了一些非常有用的答案,但目前的答案似乎没有给出我还没有实现的任何其他优化。

谢谢!

编辑:感谢这位可爱的人,他编辑了我的问题,使关键词流行起来:)。下面是一个可以运行算法的矩阵示例:

代码语言:javascript
复制
#####
#E#S#
#.#.#
#...#
#####

这应该返回值6。

EDIT2:修正了一些小错误。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-10-17 19:41:52

正如注释中所建议的,您不必存储路径。试试这个:

代码语言:javascript
复制
from collections import deque

def shortest_path_1(maze):
    wall, clear, endchar, startchar = '#', '.', 'S', 'E'
    height = len(maze)
    width = len(maze[0])

    def find_start(grid):
        for y in range(1, height-1):
            for x in range(1, width-1):
                if grid[y][x] == startchar:
                    return (x, y, 0)

    start = find_start(maze)

    queue = deque([start])

    seen = set()
    while queue:
        x, y, d = queue.popleft()

        if not 0 <= x < width:
            continue
        if not 0 <= y < height:
            continue
        if maze[y][x] == wall:
            continue

        if maze[y][x] == endchar:
            return d

        if (x, y) in seen:
            continue
        seen.add((x, y))

        queue.append((x+1, y, d+1))
        queue.append((x-1, y, d+1))
        queue.append((x, y+1, d+1))
        queue.append((x, y-1, d+1))

    return -1

maze = [x for x in """
#####
#E#S#
#.#.#
#...#
#####
""".split('\n') if x]

print shortest_path_1(maze)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52861952

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档