BFS(广度优先搜索)

简介

BFS的过程是首先访问起始结点v,接着访问顶点v的所有未被访问的邻接结点,然后对每个继续进行上述步骤,直到所有结点都被访问过为止,当然,在访问过程中,需要使用一个队列,然后类似二叉树的层次遍历来访问。

BFS通俗的来讲,就如通病毒扩散一般蔓延。往往采用BFS求解迷宫问题的入口到出口的最短路径。

运算步骤

void BFS(AdjGraph L,int v)
{
	ANode *p;
	int queue[MAXV];
	int front = 0;
	int rear = 0;
	int w;
	for(int i =0;i<L.pointsnum;i++)//初始化数组
	{
		visted[i] = 0;
	}
	cout<<" "<<L.adjlist[v].data;
	visted[v] = 1;//置已访问
	rear = (rear + 1 )% MAXV;
	queue[rear] = v;
	while(front != rear)//队列不为空循环
	{
		front = (front + 1)%MAXV;
		w = queue[front];//出队
		p = L.adjlist[w].firstarc;
		while( p != NULL)//查找所有邻接结点
		{
			if(visted[p->adjvex]==0)//当前未被访问
			{
				cout<<" "<<L.adjlist[p->adjvex].data;//打印
				visted[p->adjvex] = 1;//标记
				rear = (rear + 1) % MAXV;
				queue[rear] = p->adjvex;
			}
			p = p->nextarc;
		}
	}
}

  

猜你喜欢

转载自www.cnblogs.com/ygsworld/p/10206234.html