Breadth-First search traversal for "Introduction to Algorithms" (BFS)

Source: Internet
Author: User

How to store graphs: adjacency matrix, adjacency table

For example: There is a figure shown below (the diagram is also an example of a program):

The above graph can be expressed as follows by the adjacency matrix :


The adjacency table can be expressed as follows:


adjacency matrices can be easily represented by two-dimensional arrays, with the following main look at how the adjacency table is formed :

The adjacency table storage method is a storage method combining sequential storage and chain storage. In This approach, only the 0 elements are considered, so that storage space can be saved when there are many vertices and few edges in the graph.
The adjacency table storage structure consists of two parts : For each vertex VI, a structure array with two domains is used to store the array, which is called the vertex table. One of these domains is called the vertex domain (vertex), which holds the data information of the vertex itself, while the other is called the Pointer Field (link), which holds the storage location of the header nodes of the single linked list, which are attached to the edges of the vertex. The vertex VJ adjacent to VI are linked to a single linked list called VI adjacency list. Each node in the adjacency list is composed of two domains: one is the neighboring point Domain (Adjvex), the ordinal number J (can be the subscript of the array unit of vertex VJ in the vertex table) used to store the vertex VJ adjacent to VI; the second is the chain field (next), which links the nodes in the adjacency list. The specific procedures are implemented as follows:

void Createadjtable (Vexnode ga[n],int E)//creates adjacency table
{
	int i,j,k;
	Edgenode *s;
	printf ("\ n Enter the contents of the vertex:");
	for (i=0;i<n;i++)
	{
		Ga[i].vertex=getchar ()//Read the vertex content
		
		ga[i].link=null;//initialize
	}
	printf (\ n) );
	for (k=0;k<e;k++)
	{
		printf ("ordinal number of two vertices of the input edge:");
		scanf ("%d%d", &i,&j); The ordinal number of the two vertices that are read on the Edge
		s= (Edgenode *) malloc (sizeof (Edgenode));
		s->adjvex=j;
		s->next=ga[i].link;
		Ga[i].link=s;

		s= (Edgenode *) malloc (sizeof (Edgenode));
		s->adjvex=i;
		s->next=ga[j].link;
		Ga[j].link=s

	}
}

Breadth-First search traversal (BFS):The breadth-first search traversal of a graph is similar to a hierarchical traversal of trees. Under the assumption that the initial state is not accessible to all vertices in the graph, this method starts from a vertex vi in the graph, accesses VI first, and then accesses the adjacency point VJ of VI. After all the VJ have been accessed, the neighboring points of the VJ are accessed again VK, and so on, until all vertices of the diagram and the initial starting point VI have paths communicated are accessed. If the graph is not connected, select a vertex that has not been accessed as the starting point and repeat the process until all vertices in the diagram are accessed.
In the traversal of this method, the vertex that is accessed first, the neighboring point is also first accessed, has the first out of the feature, so you can use a queue to save the vertex has been visited to determine the access to the vertex adjacent to the order of access. To avoid repeated access to a vertex, a secondary array visited[n is also used to mark the access of vertices. In the following, we give the breadth-first search traversal algorithm with adjacency matrix and adjacency table as storage structure Bfs_matrix and bfs_adjtable:

The specific procedures are implemented as follows:

#include <stdio.h> #include <stdlib.h> #define N 5//adjacency matrix storage method typedef struct {char vexs[n];//vertex array int arcs[n
][n];

}graph;
	Adjacency Table Storage method typedef struct NODE {int adjvex;

struct Node *next;

}edgenode;
	typedef struct {char vertex;
Edgenode *link;

}vexnode;
	Queue operation typedef struct node {int data;
struct node *next;

}linklist; typedef struct {linklist *front,*rear;}

Linkqueue;
	void SetNull (Linkqueue *q)/queue Empty {q->front= (linklist *) malloc (sizeof (linklist));
	q->front->next=null;
q->rear=q->front;
	int Empty (Linkqueue *q) {if (q->front==q->rear) return 1;
else return 0;
		int Front (Linkqueue *q)/Fetch team Header element {if (Empty (q)) {printf ("queue is empty!");
	return-1;
else return q->front->next->data;
    } void ENqueue (Linkqueue *q,int x)/Queue {linklist * newnode= (linklist *) malloc (sizeof (linklist));
	q->rear->next=newnode;
	q->rear=newnode;
	q->rear->data=x;
	
q->rear->next=null; int Dequeue (LinkqueUE *q)//out team {int temp;
	Linklist *s;
		if (Empty (q)) {printf ("queue is empty!");
	return-1;
		else {s=q->front->next;
			if (s->next==null) {q->front->next=null;
		q->rear=q->front;
		else q->front->next=s->next;
		temp=s->data;
	return temp;
	} void Bfs_matrix (graph g,int k,int visited[n])/graph iterates {int i=0 according to the breadth precedence of the adjacency matrix storage;
	Linkqueue Q;
	SetNull (&AMP;Q);
	printf ("%c\n", G.vexs[k]);
	Visited[k]=1;
	ENqueue (&AMP;Q,K); while (!
		Empty (&q)) {i=dequeue (&q);
				for (int j=0;j<n;j++) {if (g.arcs[i][j]==1&&visited[j]!=1) {printf ("%c\n", G.vexs[j]);
				Visited[j]=1;
			ENqueue (&AMP;Q,J);
	}} void Createadjtable (Vexnode ga[n],int e)//create adjacency table {int i,j,k;
	Edgenode *s;
	printf ("\ n Enter the contents of the vertex:");
	for (i=0;i<n;i++) {Ga[i].vertex=getchar ();//Read the vertex content ga[i].link=null;//Initialize} printf ("\ n");
		for (k=0;k<e;k++) {printf ("ordinal number of two vertices of the input edge:"); scanf ("%d%d", &i,&j), or the ordinal number of the two vertices that are read in the margin s= (edgenodE *) malloc (sizeof (Edgenode));
		s->adjvex=j;
		s->next=ga[i].link;

		Ga[i].link=s;
		s= (Edgenode *) malloc (sizeof (Edgenode));
		s->adjvex=i;
		s->next=ga[j].link;

	Ga[j].link=s;
	} void Bfs_adjtable (Vexnode ga[],int k,int visited[n])//graph iterates {int i=0 according to the breadth of the adjacency table storage;
	Edgenode *p;
	Linkqueue Q;
	SetNull (&AMP;Q);
	printf ("%c\n", Ga[k].vertex); Whether the visited[k]=1;//tag has been visited ENqueue (&q,k);
		Empty (&q)) {i=dequeue (&q);
		P=ga[i].link;
				while (P!=null) {if (visited[p->adjvex]!=1) {printf ("%c\n", Ga[p->adjvex].vertex);
				visited[p->adjvex]=1;
			ENqueue (&q,p->adjvex);
		} p=p->next;
	} void Main () {graph G;
	Vexnode Ga[n];
	int visited[5]={0};
	int visited1[5]={0};
	g.vexs[0]= ' A ';
	g.vexs[1]= ' B ';
	g.vexs[2]= ' C ';
	g.vexs[3]= ' D ';
	g.vexs[4]= ' E ';
	int a[5][5]={{0,1,0,1,1},{1,0,1,0,1},{0,1,0,0,0},{1,0,0,0,0},{1,1,0,0,0}};
	for (int i=0;i<5;i++) for (int j=0;j<5;j++) G.ARCS[I][J]=A[I][J]; printf ("graph follows adjacentMatrix storage When breadth first traversal: \ n ");
	Bfs_matrix (g,0,visited);
	Createadjtable (ga,5);
	printf ("The graph takes precedence over the breadth of the adjacency table when it is stored: \ n");
Bfs_adjtable (ga,0,visited1); }

the results are shown below:


As you can see from the above, the results of the two approaches are different, but they are all correct, because they are related to the order in which the neighboring points are accessed.



Note: If the program is wrong, you may be using a different version of the development platform, please click the following link: explanation


Original: http://blog.csdn.net/tengweitw/article/details/17228937

Author: Nineheadedbird

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.