04 graph traversal - find the problem graph vertices

Figure BFS breadth-first traversal

Breadth-first search algorithm, also known as the breadth-first search algorithm, is a connected graph traversal policy, one of the search algorithm is the most simple graph. Dijksta single-source shortest path algorithm and minimum spanning tree algorithm Prim are used with the BFS similar ideas.

The basic idea of
Here Insert Picture Description
the pseudocode described
(1) queues the vertex v.
(2) when the queue is not empty then continue, otherwise the algorithm ends.
(3) the queue head to obtain team points v; v visits vertices and vertex v mark has been accessed.
(4) finds the first adjacent vertices of vertex v w.
(5) If the adjacent vertices v w not been accessed, then w queues.
(6) continue to look for another new vertex v adjacent vertices w, go to step (5).
Until all the neighbors are not visited vertex v processed. Go to step (2).
Refinement of the pseudocode described

Establish an access flag array visited [N], the initial value is 0, the vertex a is accessed, the corresponding element is set to an index.
(1) initialize the queue Q; visited [N] = 0;
(2) visits vertices v; visited [v] = 1 ; vertex v into the queue Q;
(. 3) the while (queue Q non empty)
v = queue Q team dequeue head element;
first neighbor vertex v w =;
the while (w present)
if w is not accessed, the access vertex w;
visited [w] =. 1;
; a vertex w queues Q
= w at vertex v a neighbor.

(BFS achieve adjacency matrix)

#include <stdio.h>
#define TRUE 1
#define FALSE 0
#define N 9 //顶点数
int Visited[N];
int AdjMatrix[N][N]=//邻接矩阵
	{{0,1,0,0,0,0,0,0,0},
	{1,0,0,0,1,1,0,1,1}, 
	{0,0,0,0,0,1,1,0,0}, 
	{0,0,0,0,1,0,0,0,1}, 
	{0,1,0,1,0,1,1,0,1}, 
	{0,1,1,0,1,0,1,0,0}, 
	{0,0,1,0,1,1,0,0,0}, 
	{0,1,0,0,0,0,0,0,0}, 
	{0,1,0,1,1,0,0,0,0}};
/*==========================================
函数功能:找顶点v相邻点i的后一个相邻点
函数输入:顶点v,v的相邻点i
函数输出:i的后一个相邻点下标,无相邻点时返回-1
=============================================*/
int FindVex(int v,int i)
{
	while (AdjMatrix[v][i]==0) i++;     
	if (i<N) return i;
	else return -1; 
}

/*==========================================
函数功能:基于邻接矩阵的BFS遍历
函数输入:图的遍历起始顶点v
函数输出:无
屏幕输出:图的BFS序列
=============================================*/
void GraphBFS(int v)
{
	int flag;
	SeqQueue struc;
	SeqQueue *sq;
	sq=&struc;
	int w,k;
	int count=0;

	initialize_SqQueue(sq);
	printf("BFS序列:");
	printf("%d ",v);
	Visited[v]=1;
	count++;
	flag=Insert_SqQueue(sq,v);			//首结点入队
	while (!Empty_SqQueue(sq))			//队列Q非空
	{
		if (count==N) break;
		k=Delete_SqQueue(sq);			//队列Q的队头元素出队,返回元素下标位
		v=sq->data[k];
		w=FindVex(v,0); 				//w=顶点v的第一个邻接点;
		while(w!=-1)
		{
            if( Visited[w]!=1)				//如果w未访问过
		   {
			   Visited[w]=1;			//置w访问标记
			   printf("%d ",w);
			   count++;
		   }
		       flag=Insert_SqQueue(sq,w);	//顶点w入队列Q
                 w=FindVex(v,w+1);		//w=顶点v的下一个邻接点
		}
	}
	printf("\n");
}

int main()
{
	GraphBFS(0);//从顶点1开始遍历,对应下标为0
	return 0;
}

Take int k - index node to be deleted.
The queue is always 0 or 1 nodes.

BFS algorithm discussed

Problem-solving algorithm steps breadth-first search:

1) Define a state node

When the breadth-first search algorithm for solving the problem, it is necessary to construct a data structure relationship between the state and the characteristics of the different states indicated.

2) determining extension rule node

The problem given conditions, from a node, may generate one or more new nodes, this process is often referred to as extension. The relationship between the nodes in the search results may generally be represented as a tree, the tree is called answer. Search algorithm search process is actually based on the initial conditions and extended rules construct a solution tree. The search process is actually a search algorithm based on initial conditions and answer tree structure and expand the rules to find nodes in line with the target state process.

Breadth-first search algorithm, the answer tree node expansion is based on the degree of their proximity to the starting node performed sequentially. A first ground layer that is first generated, while checking whether the destination node of the node generated, if not, one by one will be extended to all nodes in the first layer, the second layer obtained node, and a second check stratification point is contained destination node, ... n + 1 layer before junction extended, must consider the n-layer nodes for each possible state. Therefore, for the same layer node, the value of solving the problem is the same, we can extend them in any order. Mr principle here is to expand the first node.

3) search strategy

To facilitate searching, a table is provided to store all of the nodes. Because the breadth-first search algorithm, to satisfy the principle of the President into the node to expand, so the table storage nodes typically designed to queue data structure.
Search step is generally:
(1) a node removed from the queue header, in accordance with the extension rule checks whether it can be extended, if a new node is generated.
(2) Check the newly generated nodes to see if it already exists in the queue, if the new node have appeared in the queue, give up this node, then back to the first (1) step. Otherwise, if the new node has not appeared in the queue, then add it to the end of the queue.
(3) Check the new node if the destination node. If the new node is the destination node, the search is successful, the program ends; if the new node is not the destination node, the process returns to the first step (1), and then remove the node from the expanded head of the queue.
Search may eventually produce two nodes: find the target node, expand or complete all nodes without finding the target node.
If the target node exists on a limited level solution tree, breadth-first search algorithm will be able to find a way to ensure its optimal path, breadth-first search algorithm is particularly applicable to only obtain optimal solution. When given problems to solve for the path will have to save the source of each node, i.e. a node from which it is extended to the.

Breadth-first algorithm requires a departure from the initial node, and gradually extended in order to find the solution of the problem. If the problem is solvable, it is always in a layer on the answer tree.
Here Insert Picture Description

FIG depth first traversal DFS

Depth-first search map, similar to a tree preorder traversal, the search strategy is followed as far as possible "deep" search the map.
If it's there as a starting point but not detected edge, it is along this edge to continue to explore it. It has been found so far been carried out to all the nodes reachable from the source node.
Here Insert Picture Description
Here Insert Picture Description
DFS algorithm analysis
Here Insert Picture Description
since there is no adjacent access point in a predetermined order, depth-first sequence is not unique.

DFS算法描述:
Here Insert Picture Description
注:以上为连通图的 DFS 算法。非连通图的 DFS算法在上述连通图的算法基础上再检查是否有剩余顶点,如果仍有未访问的顶点,则另选一个尚未访问的顶点作为新的源点重复 DFS 过程,直至图中所有顶点均已被访问为止。

基于邻接矩阵的 DFS 递归方法程序实现

/*==========================================
函数功能:基于邻接矩阵的图DFS遍历递归算法
函数输入:图的遍历起始顶点v
函数输出:无
屏幕输出:图的DFS序列
=============================================*/
void GraphDFS(int i) 
{  int j;
   printf("%d ",i+1); //i+1是因为图中顶点编号从1开始,存储从0开始
   Visited[i]=1;
   for (j=0; j<N; j++)
         if ((AdjMatrix[i][j]==1) && (!Visited[j]) )
             GraphDFS(j);  		//被调用n次
}

基于邻接表的DFS递归方法程序实现
Here Insert Picture Description

/*==========================================
函数功能:基于邻接表的DFS遍历递归算法
函数输入:图的遍历起始顶点v
函数输出:无
屏幕输出:图的DFS序列
=============================================*/
void GraphDFS_L(int vi)	
//从vi出发深度优先搜索遍历图,图用邻接表表示
{	AL_AdjNode *p;
	printf("%d ",VexList[vi].vertex+1);	//访问顶点vi  
	Visited[vi]=1;            	//标记vi已被访问 
	p=VexList[vi].link;       	//取vi的边表头指针 
	while( p!=NULL )          	//依次搜索vi的邻接点 
	{
	  if (Visited[p->adjvex]==0)
	  //从vi的未曾访问过的邻接点出发进行深度优先搜索遍历
        GraphDFS_L(p->adjvex);  
	    p=p->next;
	}
} 

过程:访问(打印)->在邻接点递归
找邻接点(全部都在边表)并打印它,while循环条件内可增设一计数变量作为结束标志。

基于邻接表的非递归方法程序实现

/*==========================================
函数功能:图的DFS遍历非递归算法
函数输入:图的遍历起始顶点vi
函数输出:无
屏幕输出:图的DFS序列
=============================================*/
void DFS(int vi)
{
	SeqStack struc;
	SeqStack *s;
	int vj; 
	int flag;
	
	s=&struc;	
	initialize_SqStack( s );				//栈初始化
	Visited[vi]=1;						//访问顶点vi
	 printf("%d ",vi+1);
	flag=Push_SqStack(s,vi);				//顶点vi入栈
	while(!StackEmpty_SqStack(s))			//栈非空
	{
		vj=0;
     	flag=Get_SqStack(s, &vi);			//vi=栈顶元素(不出栈)
		//vi有邻接点且未被访问,跳出
        	while(!(AdjMatrix[vi][vj]==1 && Visited[vj]==0)) vj++;
         	if (vj<N) //访问vj
		{
			printf("%d ",vj+1);
			Visited[vj]=1;
             	flag=Push_SqStack(s,vj);		//vj进栈;
		 }
         else
		{
             flag=Pop_SqStack(s, &vi);		//vi出栈;
		}
	}
}

测试用图

需先把邻接矩阵转换成邻接表或手动输入邻接表

AdjMatrix[N][N]=
{{0,1,1,0,0,0,0,0},
{1,0,0,1,1,0,0,0},
{1,0,0,0,0,1,1,0},
{0,1,0,0,0,0,0,1},
{0,1,0,0,0,0,0,1},
{0,0,1,0,0,0,1,0},
{0,0,1,0,0,1,0,0},
{0,0,0,1,1,0,0,0}};
Here Insert Picture Description

图的遍历问题分类

遍历完所有的边而不能有重复,即所谓“一笔画问题”或“欧拉路径”;
遍历完所有的顶点而没有重复,即所谓“哈密尔顿问题”;

遍历完所有的边可以有重复,即所谓“中国邮递员问题”;
遍历完所有的顶点而可以重复,即所谓“旅行推销员问题”。

图的遍历小结
Here Insert Picture Description

发布了23 篇原创文章 · 获赞 3 · 访问量 1364

Guess you like

Origin blog.csdn.net/herui7322/article/details/104376424