Traversal __graph of graphs and graphs

Source: Internet
Author: User

Because I have not studied discrete mathematics, here can only be a fish for a while:

A graph (graph) G = (v,e) is made up of vertex set V (vertex) and Edge set E (Egge). Each edge is a point pair (v,w), where the v,w∈v. If the point pair is ordered, then the graph is a direction, otherwise it becomes a graph without direction. If two vertices (v1,v2) are ∈e, then they are related, and they are adjacent to each other. The degree of a point refers to the number of vertices associated with this point. For the direction graph, also divides into the degree and the degree. If there is a bit of sequence (V1,v2,...... vn), if the adjacent two (vi,vi+1) ∈e, they form the path. If V1=VN, it is called a loop or loop. If you can get from the point V1 along the path to V2, then call these two points is unicom. If any of the two points in the graph are unicom, then it is called a connected graph. If there is a graph G ' = (v ', E '), and V ' ∈v,e ' ∈e, then the G ' is called a sub graph of G. In particular, if the vertices of the two graphs are exactly the same, only the edge set of the second picture is the first subset, then the second is called the generating sub graph of the first picture.

The basic concept of the diagram to say so much first, in fact, after the painting of these concepts are very clear.

So this complex data structure, that is, a bit, there is a side, how to express it. People have come up with a number of representations: adjacency matrices, adjacency tables, and so on. Here we only introduce the simplest adjacency matrix: to write a n*n matrix of n vertices in a graph, if two vertices are associated, then the value of the matrix is 1, or 0.

#include <stdio.h>
#include <malloc.h>
//Depth First search needs to use stack
#include "stack.h"
// Breadth-first traversal requires the use of queues
#include "queue.h"
#define MAX 8

//adjacency matrix
typedef int** Adjacentmatrix;

The data structure of the graph is
typedef struct Graph
{
	//adjacency matrices
	Adjacentmatrix matrix;
	Vertex vector
	char* Vextex;
	Number of vertex vectors
	int vextexnum;
	The number of edges
	int arcnum;
} Graph;


Diagram of the basic Operation
//initialization graph graph
initgraph (int);

Destroy diagram
void Destroygraph (graph*);

Add a side
bool AddArc (graph*, Char, char);

Deletes a side
bool Deletearc (graph*, Char, char);

Show Figure
void Showgraph (graph*);


Graph traversal:
//Depth-first search recursive implementation of
void Do_dfs (graph*, int);
void DFS (graph*);

Depth-First search stack implements
int* Findadjacentvertex (graph*, int, int *);
void Dfs_bystack (Graph*,char);

The queue of breadth-first search realizes
void Bfs_byqueue (Graph*,char);


A data structure, the most important operation is to traverse him. There are two common methods for traversing graphs: depth-first traversal and breadth-first traversal. The depth-first traversal is similar to the first-order traversal of the two-tree, and the breadth-first traversal is similar to traversing the tree by layer.

The basic steps for breadth-first traversal are as follows:

1. Join the initial node

2. When the queue is not empty, out of the team, the node is placed in VX.

3. Locate the nodes that are adjacent to VX and have not been visited.

4. Ext. 2.

Note that after each team is out, you can do the appropriate operation, such as printing.

The basic steps for depth-first traversal are as follows:

1. The starting node pressure stack

2. If the stack is not empty, stack; the pop-up node is placed in VX.

3. Locate the nodes that are adjacent to VX and have not been visited, and press them onto the stack.

4. Ext. 2.

The corresponding code is given below:

#include "graph.h"//Diagram basic Operations//initialization graph graph initgraph (int n) {graph G;
	G.vextexnum = n;
	G.arcnum = 0;
	G.matrix = (int**) malloc (sizeof (int*) * n);

	for (int i = 0; i < n;++i) G.matrix[i] = (int*) malloc (sizeof (int) * n);

	for (int i = 0;i < n;++i) for (int j = 0; J < n;++j) G.matrix[i][j] = 0;
	G.vextex = (char*) malloc (sizeof (char) * n);
	char a = ' a ';
	for (int i = 0; i < n; ++i) g.vextex[i] = A+i;
return g;
	}//Destroy diagram void Destroygraph (graph* g) {free (G->vextex);
	G->vextex = NULL;
	for (int i = 0; i < g->vextexnum;++i) free (g->matrix[i]);
	Free (G->matrix);
	G->matrix = NULL;
	G->arcnum =-1;
G->vextexnum =-1;
	}//Add a side bool AddArc (graph* G,char Vex1,char vex2) {int m = vex1-' A ';	
	int n = vex2-' A '; if (M < 0 | | m > G->vextexnum | | n < 0 | | n > G->vextexnum) {printf ("2 vertexes must in the graph\n"
		);
	return false;
		else {G->matrix[m][n] = 1;
		G-&GT;MATRIX[N][M] = 1;
		++g->arcnum; Return TRue
	}///delete a side bool Deletearc (graph* G,char Vex1,char vex2) {int m = vex1-' a ';
	int n = vex2-' A ';
		if (0 = = G->matrix[m][n]) {printf ("This arc does not exsit!\n");
	return false;
		else {G->matrix[m][n] = 0;
		G->matrix[n][m] = 0;
		g->arcnum--;
	return true;
	}//Show figure void Showgraph (graph* g) {printf ("");
	for (int i = 0; i < g->vextexnum;++i) printf ("%c", G->vextex[i]);
		for (int i = 0; i < g->vextexnum;++i) {printf ("\ n");
		printf ("%c", G->vextex[i]);
	for (int j = 0;j < G->vextexnum;++j) printf ("%d", g->matrix[i][j]);
printf ("\ n");
//Graph Traversal://Depth-First search recursive implementation//need to use global variables to record whether a vertex has been visited by BOOL Visited_dfs[max];
	void DFS (graph* g) {printf ("Use recursive depth precedence traversal: \ n sequentially Access node:");
	All nodes have not been accessed for (int i = 0;i < g->vextexnum;++i) Visited_dfs[i] = False until the access is started;
	For each node, if it is not accessed, call the depth-first search for (int i = 0; i < g->vextexnum;++i) {if (false = Visited_dfs[i]) Do_dfs (g,i);
printf ("\ n"); } void Do_dfs (graph* g,int I) {Visited_dfs[i] = true;
	printf ("%c", G->vextex[i]); Search for the adjacency point of I for (int j = 0; J < g->vextexnum;++j) {//If J is the adjacency point of I and has not been accessed, the J call Depth First search if (visited_dfs[j] = = False &
	amp;& 1 = g->matrix[i][j]) Do_dfs (G,J);
	} void Dfs_bystack (graph* g,char start) {int start = start-' A ';
	printf ("Use queues for depth first traversal: \ n Sequentially access nodes:");
	An array is established to mark whether the node has been visited bool *is_visited = (bool*) malloc (sizeof (BOOL) * g->vextexnum);
	for (int i = 0;i < g->vextexnum;++i) Is_visited[i] = false;
	Build a stack of stacks s;
	s = initstack (G->vextexnum);
	Push (&s,start);
	Is_visited[start] = true;
		while (!is_empty (&s)) {int vertex;
		Pop (&s,&vertex);
		int adjacentnumber;
		int* Adjacentvertex = Findadjacentvertex (G,vertex,&adjacentnumber); for (int i = 0;i < Adjacentnumber;++i) {if (false = = Is_visited[adjacentvertex[i]]) {push (&s,adjacentve
				Rtex[i]);
			Is_visited[adjacentvertex[i]] = true;
	} printf ("%c", G->vextex[vertex]); printf ("\ n");
	Destroystack (&s);
Free (is_visited);
	//Find the node adjacent to the Vex, through n with the number of nodes, return the array of these node int* Findadjacentvertex (graph* g,int vex,int *n) {//counter int cnt = 0;
	int* adj = (int*) malloc (sizeof (int) * g->vextexnum);
	for (int i = 0;i < G->vextexnum;++i) {if (1 = = G->matrix[vex][i]) adj[cnt++] = i;
	} *n = cnt;
return adj;
	} void Bfs_byqueue (Graph *g,char start) {int start = start-' A ';
	printf ("Use stack for breadth first traversal: \ n sequentially Access node:");
	An array is established to mark whether the node has been visited bool *is_visited = (bool*) malloc (sizeof (BOOL) * g->vextexnum);
	for (int i = 0;i < g->vextexnum;++i) Is_visited[i] = false;
	Queue Q;
	Q = Initqueue (g->vextexnum);
	Enqueue (&q,&start);
	Is_visited[start] = true;
		while (!is_empty (&q)) {int vertex;
		Dequeue (&q,&vertex);
		int adjacentnumber;
		int* Adjacentvertex = Findadjacentvertex (G,vertex,&adjacentnumber); for (int i = 0; i < adjacentnumber;++i) {if (false = = Is_visited[adjacentvertex[i]]) {Enqueue (&q,& Adjacentvertex[i]);
			Is_visited[adjacentvertex[i]] = true;
	} printf ("%c", G->vextex[vertex]);
	Free (is_visited);
Destroyqueue (&AMP;Q); }


Note that the depth-first traversal of the graph can be implemented either by using stacks or by using the return implementation. This is in line with our previous understanding.

The stack and queue code used in the program is not posted, before the blog has been introduced. The main difference is that this time you get a stack or queue by the return value of the function, which used to pass the pointer to them to the function. But the two ideas are very similar.

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.