【coding】Breadth-first Search 广度优先搜索(原理+代码实现)

回顾了运筹课写的图搜索作业,并重新编程实现了一下。

本次更新添加一些汉语注释。2023.10.2

1. 广度优先搜索

1.1 题目描述

Use Breath-first search and Depth-first search to search graph below. Illustrate each execution step.
在这里插入图片描述

1.2 题解

只有三种点,用队列实现(先进先出)

  • 探索过的点(黑色)-出队列
  • 正在被探索的点(灰色)-在队列中
  • 待探索的点(白色)-尚未进入队列
  • For G = (V;E) and a source vertex s, it systematically explores the edges of G to discover every vertex that is reachable from s
  • Breadth-first search expands the frontier between discovered and undiscovered vertices uniformly across the breadth of the frontier
  • color[u]:
    • white (undiscovered),
    • gray (discovered but not scanned)
    • black (discovered and scanned)

① V={s,u,v,w,x,y,z}
② Adjacency-list:
在这里插入图片描述
在这里插入图片描述

1.3 编程实现

数据准备

def primalData():
    graph = {
        's': ['v', 'x'],
        'u': ['v', 'x', 'y', 'z'],
        'v': ['s', 'u', 'w'],
        'w': ['v'],
        'x': ['s', 'u', 'y'],
        'y': ['u', 'x', 'z'],
        'z': ['u', 'y']
    }
    return graph

from collections import deque


class Search():
    def __init__(self, graph, start_point):
        self.graph = graph
        self.start_point = start_point

    def BFS(self):
        res = []  # 储存搜索结果
        queue = deque(self.start_point)  # 广度优先搜索的辅助队列,用collections.deque实现
        visited_set = set()  # 储存访问过的点集合,防止重复访问
        while queue:  # 当队列中存在元素时
            n = len(queue)  # 获取队列长度,只获取这一次,后面再添加的不算在这一层中
            temp = []  # 放这一层的元素
            for _ in range(n):  # 对于队列(这一层)中的每个元素
                cur = queue.popleft() 
                temp.append(cur)
                visited_set.add(cur)
                neighbours = self.graph[cur]  # cur的临接点
                for neighbour in neighbours:
                    if neighbour not in visited_set:  # 判断是否为探索过的元素
                        queue.append(neighbour)
                        visited_set.add(neighbour)
            res.append(temp)
        return res


if __name__ == '__main__':
    search = Search(primalData(), 's')
    res = search.BFS()
    print(res)
# 输出展示:
[['s'], ['v', 'x'], ['u', 'w', 'y'], ['z']]

2. 其他图搜索资料

2.1 Dijkstra

适用范围:无负权重边
参考文章链接:有概念讲解
参考文章链接:有示例

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值