基础算法——BFS

以二阶矩阵存储

def graph_bfs(graph, s):
    color = []
    queue = []  # 记录访问过的顶点
    count = 0
    n = len(graph)
    for v in range(n):
        color.append(0)
    queue.append(s)
    count = count + 1
    color[s] = 1
    while queue:
        temp = queue[0]
        print(temp)
        # 下面是把color不为1的graph[count - 1]里的item放进Q
        if count - 1 < n:
            for i in graph[count - 1]:
                if color[i] == 0:
                    queue.append(i)
        queue.remove(temp)
        count = count + 1
        # 放进Q里的item变颜色
        for v in queue:
            color[v] = 1


if __name__ == '__main__':
    graph_test = [[1, 2, 3], [5], [], [4], [5], []]
    graph1 = [[1], [2, 3, 4], [3, 4], [], []]
    graph2 = [[1, 2], [3], [0, 4, 5], [], [2, 5, 7], [2, 4, 7, 6], [5, 7], [4, 5, 6]]
    source = 0
    graph_bfs(graph2, source)

以字典存储

import collections


def breadth_first_search(graph, root):
    # visited存储被访问过的节点
    # queue是一个队列,记录正在遍历的点
    visited, queue = set(), collections.deque([root])
    while queue:
        vertex = queue.popleft()  # 弹出队列中的第一个元素
        print(vertex)  # 输出此时弹出的结果
        print(visited)
        for neighbour in graph[vertex]:  # 找到当前顶点对应的邻居节点graph[0]=[1,2]
            if neighbour not in visited:  # 如果当前找到的邻居节点没有被访问过
                visited.add(neighbour)
                queue.append(neighbour)



if __name__ == '__main__':
    graph_test = {0: [2, 3], 2: [4, 5], 3: [1, 4], 1: [4], 4: [5], 5: []}
    breadth_first_search(graph_test, 0)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值