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

BFS 搜索算法

如何解决BFS 搜索算法

我刚开始学习 Python,我正在尝试创建一个 bfs 算法,该算法可以获取加权图的顶点并返回 bfs。最终,我需要将加权边添加到顶点,以便我可以计算行进的距离,但是我能够让 bfs 单独处理我的顶点。这是到目前为止的代码

# Python implementation to find the
# shortest path in the graph using
# dictionaries

# Function to find the shortest
# path between two nodes of a graph
def BFS_SP(graph,start,goal):
    
    explored = []
    
    # Queue for traversing the
    # graph in the BFS
    queue = [[start]]
    
    # If the desired node is
    # reached
    if start == goal:
        print("Same Node")
        return
    
    # Loop to traverse the graph
    # with the help of the queue
    while queue:
        path = queue.pop(0)
        node = path[-1]
        
        # Condition to check if the
        # current node is not visited
        if node not in explored:
            neighbours = graph[node]
            
            # Loop to iterate over the
            # neighbours of the node
            for neighbour in neighbours:
                new_path = list(path)
                new_path.append(neighbour)
                queue.append(new_path)
                
                # Condition to check if the
                # neighbour node is the goal
                if neighbour == goal:
                    print("Shortest path = ",*new_path)
                    return
            explored.append(node)

    # Condition when the nodes
    # are not connected
    print("So sorry,but a connecting"\
                " path doesn't exist :(")
    return
# Driver Code
if __name__ == "__main__":
    
    # Graph using dictionaries
    graph = {
        'arad':             ['Zerind','Timisoara','Sibiu'],'Bucharest':        ['Urziceni','Giurgiu','Pitesti','Fagaras'],'Craiova':          ['dobreta','Rimnicu Vilcea'],'dobreta':          ['Mehadia','Craiova'],'Eforie':           ['Hirsova'],'Fagaras':          ['Sibiu','Bucharest'],'Giurgiu':          ['Bucharest'],'Hirsova':          ['Eforie','Urziceni'],'Iasi':             ['Neamt','Vaslui'],'Lugoj':            ['Mehadia','Timisoara'],'Mehadia':          ['Lugoj','dobreta'],'Neamt':            ['Iasi'],'Oradea':           ['Zerind','Pitesti':          ['Rimnicu Vilcea','Bucharest','Rimnicu Vilcea':   ['Sibiu','Sibiu':            ['Rimnicu Vilcea','Fagaras','arad','Oradea'],'Timisoara':        ['Lugoj','arad'],'Urziceni':         ['Bucharest','Hirsova'],'Vaslui':           ['Iasi','Zerind':           ['Oradea','arad']
    }
    
    # Function Call
    BFS_SP(graph,'Bucharest')

我需要我的图形数组实际上看起来像这样:

graph = {
    'arad':             [['Zerind',75],['Timisoara',118],['Sibiu',140]],'Bucharest':        [['Urziceni',85],['Giurgiu',90],['Pitesti',101],['Fagaras',211]],'Craiova':          [['dobreta',120],138],['Rimnicu Vilcea',146]],'dobreta':          [['Mehadia',['Craiova',120]],'Eforie':           [['Hirsova',86]],'Fagaras':          [['Sibiu',99],['Bucharest','Giurgiu':          [['Bucharest',90]],'Hirsova':          [['Eforie',86],['Urziceni',98]],'Iasi':             [['Neamt',87],['Vaslui',92]],'Lugoj':            [['Mehadia',70],111]],'Mehadia':          [['Lugoj',['dobreta',75]],'Neamt':            [['Iasi',87]],'Oradea':           [['Zerind',71],151]],'Pitesti':          [['Rimnicu Vilcea',97],138]],'Rimnicu Vilcea':   [['Sibiu',80],'Sibiu':            [['Rimnicu Vilcea',['arad',140],['Oradea','Timisoara':        [['Lugoj',111],118]],'Urziceni':         [['Bucharest',['Hirsova','Vaslui':           [['Iasi',92],142]],'Zerind':           [['Oradea',75]]
}

而且我对如何修改我的代码以将新版本的图形作为单个节点感到有些茫然。如果我在旧代码中实现了我需要的新图,我会收到一条错误消息:

Traceback (most recent call last):
  File "/Users/meikebuettner/hello/astar_test.py",line 79,in <module>
    BFS_SP(graph,'Bucharest')
  File "/Users/meikebuettner/hello/astar_test.py",line 30,in BFS_SP
    neighbours = graph[node]
TypeError: unhashable type: 'list'

任何见解、帮助、想法或研究主题都将不胜感激!谢谢!!

解决方法

问题是由于您将节点(新数据结构中的列表)添加到 new_path

for neighbour in neighbours: # neighbour: ['Rimnicu Vilcea',97]
    ...
    new_path.append(neighbour)

new_path 应该只包含节点的名称,而不是名称和权重。

我们可以修正为:

for neighbour_node in neighbours:
    neighbour = neighbour_node[0]
    ...

提出此建议的原因:

    在这种情况下,
  • neighbour_node 是比邻居更正确的名称,因为它代表节点,而不是邻居的名称。
  • 我们可以在不修改该行的情况下修复邻居和目标的比较
# Condition to check if the
# neighbour node is the goal
if neighbour == goal:

注意:有多种方法可以修复您的代码,我的只是其中一种。你可以试试其他的,比如改变 pathnew_path 的数据结构。

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