Data structure - Breadth-first traversal of the graph (BFS)

——The content of this section is the video content notes of P59 of Bilibili Wangdao Postgraduate Entrance Examination "Data Structure".


Table of contents

1. Connection with breadth-first traversal of trees

1. Breadth-first traversal of the tree (level traversal)

(1) Algorithm steps

(2) Algorithm demonstration

(3) Features

 2. Breadth-first traversal of the graph

(1) Algorithmic thinking

(2) Features

(3) Algorithm steps

2. BFS algorithm

1. Code implementation

2. Code explanation

(1) BFS function

(2) BFSTraverse function

3. Breadth-first traversal of sequence

1. Adjacency matrix

2. Adjacency list

4. Complexity Analysis

1. Adjacency matrix

2. Adjacency list

5. Breadth-first spanning tree


1. Connection with breadth-first traversal of trees

1. Breadth-first traversal of the tree (level traversal)

(1) Algorithm steps

        ​ ​ ①Initialize an auxiliary queue;

        ​ ​ ②The root node joins the team;

        ③ If the queue is not empty, the head node of the queue is dequeued, and the node is accessed, and then its left and right subtree nodes are inserted into the tail of the queue (if any);

(2) Algorithm demonstration

(3) Features

        There is no "loop". When searching for adjacent nodes, it is impossible to search for nodes that have been visited.


 2. Breadth-first traversal of the graph

(1) Algorithmic thinking

        Start from the specified node to access, then find adjacent nodes to access, and repeat until all nodes are accessed;

(2) Features

        When searching for adjacent nodes, it is possible to find nodes that have already been visited;

(3) Algorithm steps

        ① Find all vertices adjacent to a vertex (use FirstNeighbor(G,x) and NextNeighbor(G,x,y)two basic operations to achieve);

        ② Mark which vertices have been visited (define bool array: bool visited[MAX_VERTEX_NUM]; to mark whether each vertex has been visited visited);

        ③Need aauxiliary queue;


2. BFS algorithm

1. Code implementation

bool visited[MaxVertexNum];				//访问标记数组

void BFSTraverse(MGraph G)				//对图G进行广度优先遍历
{
	for (int i = 1; i < G.vexnum; ++i)
		visited[i] = false;				//访问标记数组初始化
	InitQueue(Q);						//初始化辅助队列Q
	for (int i = 0; i < G.vexnum; ++i)	//从1号顶点开始遍历
		if (!visited[i])				//对每个连通分量调用一次BFS
			BFS(G, i);					//vi为访问过,从vi开始BFS
}

void BFS(MGraph G, int v)				//从顶点v出发,广度优先遍历图G
{	
	visit(v);							//访问初始顶点v
	visited[v] = true;					//对v做已访问标记
	EnQueue(Q, v);						//顶点v入队列Q
	while (!isEmpty(Q))
	{
		DeQueue(Q, v);					//顶点v出队
		for (w = FirstNeighbor(G, v); w >= 0; w = NextNeighbor(G, v, w))	//检测v所有邻接点
			if (!visited[w])			//w为v的尚未访问的邻接顶点
			{
				visit(w);				//访问顶点w
				visited[w] = true;		//对w做已访问标记
				EnQueue(Q, w);			//顶点w入队列
			}
	}
}

2. Code explanation

(1) BFS function

        ​ ​ ① Starting from vertex v, traverse the graph G breadth-first;

        ​ ​ ②After accessing the node, it is marked as true;

        ​ ​ ③Join the team after completing the visit;

        ④While loop: When the team is not empty, the head element of the team is dequeued, Note here that the second formal parameter of the dequeue operation will receive the dequeue element, and then enter the v value into the back The for loop to access the vertices adjacent to the vertex just dequeued;

        ⑤for loop: w=the first adjacent point of the element just dequeued, perform access, mark, and enqueue operations, and then find the next point adjacent to the element just dequeued until there are no adjacent points , at this timew=-1<0 returned by NextNeighbor, exit the for loop;

        ​​​​​⑥if loop: If it has not been marked as true, access, mark, and join the queue.

(2) BFSTraverse function

        ①This function is mainly used in the case of "disconnected graph", because BFS can only traverse all nodes connected to the specified node; if it is a non-connected graph , you need to determine whether there are any elements that have not been marked as true, and perform BFS on them;

        ​ ​ ②Initialize the access tag array first;

        ​ ​ ③Initialize the auxiliary queue;

        ​ ​ ④Start traversing from node 1, and call BFS once for each connected component (maximal connected subgraph);

        ⑤For an undirected graph, the number of calls to the BFS function = the number of connected components;


3. Breadth-first traversal of sequence

1. Adjacency matrix

        The adjacency matrix representation of the same graph is unique, so the breadth-first traversal sequence is unique;

2. Adjacency list

        The adjacency list representation of the same graph is not unique, so the breadth-first traversal sequence is not unique;


4. Complexity Analysis

1. Adjacency matrix

(1) Accessing |V| vertices requires O(|V|) time;

(2) It takes O(|V|) time to find the adjacent points of each vertex, and there are a total of |V| vertices;

(3) The sum of the two isO(|V|)+O(|V|^{2}), so the time complexity =O(|V|^{2});


2. Adjacency list

(1) Accessing |V| vertices requires O(|V|) time;

(2) It takes O(|E|) time to find the adjacent points of each vertex;

(3) Therefore time gain =O(|V|+|E|);


5. Breadth-first spanning tree

1. Each time an adjacent node is visited, the node visited for the first time is used as a tree composed of child nodes;

2. The breadth-first spanning tree is determined by the breadth-first traversal process. Since the representation of the adjacency list is not unique, the breadth-first spanning tree based on the adjacency list is not unique either;

3. For breadth-first traversal of non-connected graphs, a breadth-first generated forest can be obtained.

Guess you like

Origin blog.csdn.net/weixin_64084604/article/details/128346899