2.(图)-广度优先遍历BFS

        从图的某个节点开始遍历,访问了则标记下来,然后遍历此点邻域中且未访问的点为新起点,且做上访问标记,通常通过递归和队列的技巧实现。

1:以1为起点,[2,5]入队列

2:取出2,相邻且未标记访问的3,4入[5,3,4]

3:取出5,入3,4;[3,4,3,4]

4:取出3,入4;[4,3,4,4]

5:取出4,剩余[3,4,4]

6:[3,4,4]均被标记访问,依次弹出,不打印、访问节点

最终深度优先遍历依次访问节点:1,2,5,3,4

from collections import deque


class list_node:
    def __init__(self):
        self.val = 0
        self.next = None


def bfs(current):
    '''
    广度优先遍历
    :param current:起点
    :return:
    '''
    node_deque = deque([])
    if len(node_deque) == 0:
        node_deque.append(current)
    # 节点访问标记
    run = [0] * 9
    while len(node_deque) != 0:
        out = node_deque.popleft()
        if run[out] == 0:
            print('[%d]' % out, end=' ')
            run[out] = 1
        ptr = head[out].next
        while ptr != None:  # 遍历所有current节点连接的节点
            if run[ptr.val] == 0:  # 连接点未访问
                node_deque.append(ptr.val)
            ptr = ptr.next


def print_head(head):
    '''
    打印函数
    :return:
    '''
    for i in range(len(head)):
        ptr = head[i]
        print('顶点%d=>' % i, end=' ')
        ptr = ptr.next
        while ptr != None:
            print('[%d] ' % ptr.val, end=' ')
            ptr = ptr.next
        print()


def graph_create(data):
    '''
    创建链表表示图
    :return:
    '''
    global head
    for i in range(len(head)):
        head[i] = list_node()
        head[i].val = i
        head[i].next = None
        ptr = head[i]
        for j in range(len(data)):
            if data[j][0] == i:
                newnode = list_node()
                newnode.val = data[j][1]
                newnode.next = None
                ptr.next = newnode
                ptr = ptr.next

data = [[1, 2], [2, 1], [1, 3], [3, 1],
        [2, 4], [4, 2], [2, 5], [5, 2],
        [3, 6], [6, 3], [3, 7], [7, 3],
        [4, 5], [5, 4], [6, 7], [7, 6],
        [5, 8], [8, 5], [6, 8], [8, 6]]
head = [None] * 9
graph_create(data)
print_head(head)

print('1节点开始,广度优先遍历:')
bfs(1)
print()

output:

顶点0=> 
顶点1=> [2]  [3]  
顶点2=> [1]  [4]  [5]  
顶点3=> [1]  [6]  [7]  
顶点4=> [2]  [5]  
顶点5=> [2]  [4]  [8]  
顶点6=> [3]  [7]  [8]  
顶点7=> [3]  [6]  
顶点8=> [5]  [6]  
1节点开始,广度优先遍历:
[1] [2] [3] [4] [5] [6] [7] [8] 

原文地址:https://www.cnblogs.com/onenoteone/p/12441753.html