Rewriting of BFS & DFS

Since I saw the problem of rewriting the recursive form of mid-order traversal to non-recursive form in the review of the data structure, I tried to rewrite the two classic traversal algorithms in the figure.

Non-recursive implementation of DFS

void DFS(Graph *g,int v)
{
	arcnode *p;//边链表头指针
	int visited[g.Vnum],stack[g.Vnum],top=-1;
	for(int i=0;i<g.Vnum;i++)
	{
		visited[i]=0;
	} 
	visit(v);  //访问结点v 
	top++;
	stack[top]=v;
	while(top!=-1)
	{
		v=stack[top];
		top--;
		p=g.addlist[v].firstarc;
		while(p!=NULL&&visited[p->data]==1)
		{
			p=p->nextacr; 
		}
		if(p==NULL) --top;
		else
		{
			v=p->data;
			visit(v);
			visited[v]=1;
			top++;
			stack[top]=v;
		}
	}
} 

Queue implementation BFS

void BFS(Graph g,int v)
{
	arcnode *p;//边链表头指针
	int visited[g.Vnum],stack[g.Vnum],top=-1;
	for(int i=0;i<g.Vnum;i++)
	{
		visited[i]=0;
	} 
	visit(v);  //访问结点v 
	top++;
	stack[top]=v;
	while(top!=-1)
	{
		v=stack[top];
		top--;
		p=g.addlist[v].firstarc;
		while(p!=NULL)
		{
			if(visited[p->data]==0)
			{
				v=p->data;
			    visit(v);
				visited[v]=1;
			    top++;
			    stack[top]=v;
			}
			p=p->nextacr; 
		}
	}
} 
Published 28 original articles · won praise 2 · Views 3259

Guess you like

Origin blog.csdn.net/Maestro_T/article/details/86241110