Graph: adjacency matrix creation, depth-first traversal, and breadth-first traversal

Source: Internet
Author: User
Tags arrays
Introduction to adjacency matrices

Directly, the adjacency matrix is a storage structure of graphs . So what's the picture? A diagram is a logical structure that, like a linear structure, a tree structure, and a collection structure, is a logical structure used to describe the relationship between data elements in a data object . Take a look at the definition of the graph: a graph is a set of vertices that have poor non-empty sets and edges between vertices, usually expressed as G (V,e) where G represents a graph, V is a set of vertices in Figure g, and E is a set of edges in Figure G .

Consider that the figure is composed of vertices and edges or arcs 2 parts. It is difficult to fit together, it is natural to consider a 2 structure to store separately.

the adjacency matrix (adjacency matrix) of graphs is stored using 2 arrays to represent the graph. A one-dimensional array stores information about vertices in a graph, and a two-dimensional array, called an adjacency matrix, stores information about edges or arcs in a diagram . adjacency matrix creation diagram

Any algorithm, our first consideration is certainly the data structure, then the adjacency matrix method, the graph data structure is very good expression. Contains vertex arrays, adjacency matrices, and, of course, the number of vertices and the number of edges. The data structure is serviced for the algorithm. Data structure of the graph:

typedef struct
{
Vertextype vertex[max_vertex];//Vertex set
Edgetype edge[max_vertex][max_vertex];//Edge Set
int Vertexnum, edgenum;//vertex number, number of edges
}mgraph;

After the data structure of the graph is clear, the algorithm to create the graph is actually an assignment of the graph content . createmgraph function

The adjacency matrix creates an mgraph* mesh,
createmgraph ()
{
	mgraph* mgraph = (mgraph*) malloc (sizeof (Mgraph
	)); int Vertexnum, edgenum;
	printf ("Please enter the number of vertices and the number of sides (please separate them with commas):");
	scanf ("%d,%d", &vertexnum, &edgenum);
	Mgraph->vertexnum = Vertexnum;
	Mgraph->edgenum = Edgenum;
	GetChar ();//Remove the last input of the newline
	printf ("Enter vertex value:");
	Enter the vertex value
	for (int i = 0; i < vertexnum; i++)
	{
		scanf ("%c", &mgraph->vertex[i]);
	}
	Initialize the set of edges for
	(int i = 0; i < vertexnum; i++)
	{for
		(int j = 0; J < Vertexnum; J + +)
		{
			mgraph ->EDGE[I][J] = INFINITY;
		}
	}
	Input Edge value
	for (int i = 0; i < edgenum; i++)
	{
		int i, J, W;
		printf ("Please input (VI,VJ) the corresponding vertex of the subscript and weights (separated by commas):");
		scanf ("%d,%d,%d", &i, &j, &w);
		MGRAPH->EDGE[I][J] = mgraph->edge[j][i] = w;//No direction graph is symmetric matrix
	}
	return mgraph;

Depth-first traversal of adjacency matrices

First, the graph traversal: from a vertex in the graph to visit the remaining vertices in the graph, and so that each vertex is accessed only once, this process is called graph traversal (traversing graph). So what is depth-first traversal? Depth-priority traversal (Depth first search), also known as depth-first search, is referred to as DFS. think about it because there are a lot of roads in the diagram, how to access a place and no longer access the visited vertices. In fact, there are 2 kinds of solutions, corresponding to our 2 kinds of traversal mode. One scenario: each vertex in the graph is connected with a number of vertices, we can go from a node V, access the node, and then access the non-visited neighboring points of V, and then continue to access the node's inaccessible neighboring points, a bit like the meaning of a follow-up, until all the vertices in the diagram have been accessed so far. Do you feel like you can use recursion? Be sure to use a global array to record whether the vertex has access to the chant, visit the next time do not visit the chant. The following is the depth-first traversal of the adjacency matrix:

void Dftmgraph (mgraph* graph,int vexindex)
{
	//access is no longer accessed
	if (g_visited[vexindex] = TRUE)
	{
		return;
	}
	G_visited[vexindex] = TRUE;
	Operate
	Visitmgraphvertex (Graph->vertex[vexindex])

	for access to the node. for (int j = 0; J < graph->vertexnum; J + +)
	{
		//weights not zero, continuing access to next node
		if (graph->edge[vexindex][j]! = 0)
		{
			dftmgraph (graph, j);
		}
	}
	return;
}

Depth-first traversal of
void Traversemgraph (mgraph* graph)
{
	if (NULL = = Graph)
	{
		return;
	}
	The set node has not been visited for
	(int i = 0; i < graph->vertexnum; i++)
	{
		g_visited[i] = FALSE;
	}
	for (int i = 0; i < graph->vertexnum; i++)
	{
		if (g_visited[i] = = FALSE)
		{
			dftmgraph (graph,i); 
  }
	}
	return;
}

breadth-first traversal of adjacency matrices

breadth-First search, also known as breadth-first breath, detects BFS. It is similar to a sequence traversal, starting from a node V in the diagram, accessing the adjacency points that the node has not visited, and then accessing the inaccessible neighboring nodes that have visited the nodes until all the nodes in the diagram have been accessed. The following is the breadth-first traversal of the adjacency matrix:

//breadth-first traversal adjacency matrix void bftmgraph (mgraph* graph) {queue queue;
	Initqueue (&queue);
	for (int i = 0; i < graph->vertexnum; i++) {g_visited[i] = FALSE;
			} for (int i = 0; i < graph->vertexnum; i++) {if (g_visited[i] = = FALSE) {G_visited[i] = TRUE;
			Visitmgraphvertex (Graph->vertex[i]); EnQueue (&queue,i);//The current node subscript the queue//Why here to cycle out of the team. Out of the queue gets the subscript that has been visited over the node, and in the inner layer for continuing access to the associated junction point, the outer for loop is reduced to enter the IF number while (!
				Emptyqueue (&queue)) {int vexindex; DeQueue (&queue, &vexindex);//The node that is visited is marked out team for (int j = 0; J < graph->vertexnum; J + +) {//Connect the node and no visited node access, then Enqueue if (graph->edge[vexindex][j]! = 0 && graph->edge[vexindex][j]! = INFINITY && ;
						G_VISITED[J] = = FALSE) {G_visited[j] = TRUE;
						Visitmgraphvertex (Graph->vertex[j]);
					EnQueue (&queue, graph->vertex[j]);
}}}}} return; }

Code Summary Queue.h

#pragma once
#ifndef __queue_h__
#define __QUEUE_H__

typedef int ELETYPE;//Element type
typedef enum {ERROR, OK} Status;
typedef enum {false,true} Boolean;

Queue node
typedef struct QUEUENODE
{
	eletype data;
	struct queuenode* next;
} Queuenode;

Queue
typedef struct Queue
{
	queuenode* front;
	queuenode* tail;
} Queue;

Queue initialization
void Initqueue (queue* queue);

Queued
int EnQueue (queue* Queue, eletype data);

Out
of Team int DeQueue (queue* Queue, eletype* data);

Whether the queue is empty
int emptyqueue (queue* queue);

#endif//!__queue_h__

queue.c
#include <stdlib.h> #include "Queue.h"//Queue initialization void Initqueue (queue* queue) {Queue->front = NULL;
	Queue->tail = NULL;
Return
	}//Queue int EnQueue (queue* queue, eletype data) {if (NULL = = queue) {return ERROR;
	} queuenode* node = (queuenode*) malloc (sizeof (Queuenode));
	Node->data = data;
	Node->next = NULL;
	if (Queue->front = = NULL) {Queue->front = Queue->tail = node;
		} else {queue->tail->next = node;
	queue->tail = node;
} return OK;
	}//out of the queue int DeQueue (queue* queue, eletype* data) {if (NULL = = queue) {return ERROR; } if (!
		Emptyqueue (queue)) {queuenode* node = queue->front;
		*data = node->data;
		Queue->front = queue->front->next;
			if (NULL! = node) {Free (node);
		node = NULL;
		}//After the last element of the queue is out of the queue, the tail pointer is also set to NULL if (Emptyqueue (queue)) {Queue->tail = queue->front;
}} return OK;
	}//Whether the queue is empty int emptyqueue (queue* queue) {if (NULL = = queue) {return ERROR; } if (queue->front = = NULL) {return TRUE;
} return FALSE; }

mgraph.c

#define _crt_secure_no_warnings #include <stdio.h> #include <stdlib.h> #include "Queue.h" #define Max_ VERTEX #define INFINITY 65535 typedef char vertextype;//vertex type typedef int edgetype;//Edge weight value type typedef struct {Vertextyp
E vertex[max_vertex];//vertex set Edgetype edge[max_vertex][max_vertex];//edge set int vertexnum, edgenum;//vertex number, edge number}MGraph; Boolean G_visited[max_vertex] = {0};//global variable vertex access flag array//adjacency matrix create no-map mgraph* createmgraph () {mgraph* mgraph = (mgraph*) Mall
	OC (sizeof (mgraph));
	int Vertexnum, edgenum;
	printf ("Please enter the number of vertices and the number of sides (please separate them with commas):");
	scanf ("%d,%d", &vertexnum, &edgenum);
	Mgraph->vertexnum = Vertexnum;
	Mgraph->edgenum = Edgenum;
	GetChar ();//Remove the last input of the newline printf ("Enter vertex value:");
	Enter the vertex value for (int i = 0; i < Vertexnum; i++) {scanf ("%c", &mgraph->vertex[i]); }//Initialize the edge set for (int i = 0; i < Vertexnum; i++) {for (int j = 0; J < Vertexnum; J + +) {mgraph->edge[i][
		j] = INFINITY; }}//input edge value for (int i = 0; i < Edgenum; i++) {int I,J, W;
		printf ("Please input (VI,VJ) the corresponding vertex of the subscript and weights (separated by commas):");
		scanf ("%d,%d,%d", &i, &j, &w);
MGRAPH-&GT;EDGE[I][J] = mgraph->edge[j][i] = w;//No direction graph is symmetric matrix} return mgraph;
	}//Print the adjacency matrix of the graph data void Printmgraph (mgraph* mgraph) {printf ("Vertex array data: \ n");
	for (int i = 0; i < mgraph->vertexnum; i++) {printf ("%c", Mgraph->vertex[i]);
	} printf ("\ n Edge point Group data: \ n"); for (int i = 0, i < mgraph->vertexnum; i++) {for (int j = 0; J < mgraph->vertexnum; J + +) {printf ("%d
		\ t ", mgraph->edge[i][j]);
	} printf ("\ n");
	}}//access vertex element void Visitmgraphvertex (Vertextype data) {printf ("%c", data);
Return
	} void Dftmgraph (mgraph* graph,int vexindex) {//accessed will no longer be accessed if (g_visited[vexindex] = TRUE) {return;
	} G_visited[vexindex] = TRUE;

	Operate Visitmgraphvertex (Graph->vertex[vexindex]) for access to the node. for (int j = 0; J < graph->vertexnum; J + +) {//weight nonzero, continue access to next node if (graph->edge[vexindex][j]! = 0) {DFT
		Mgraph (graph, j);
}} return; }//Depth FirstTraverse void Traversemgraph (mgraph* graph) {if (NULL = = graph) {return;
	}//Set node has not been visited for (int i = 0; i < graph->vertexnum; i++) {g_visited[i] = FALSE;
		} for (int i = 0; i < graph->vertexnum; i++) {if (g_visited[i] = = FALSE) {dftmgraph (graph,i);
}} return;
	}//breadth-first traversal adjacency matrix void bftmgraph (mgraph* graph) {queue queue;
	Initqueue (&queue);
	for (int i = 0; i < graph->vertexnum; i++) {g_visited[i] = FALSE;
			} for (int i = 0; i < graph->vertexnum; i++) {if (g_visited[i] = = FALSE) {G_visited[i] = TRUE;
			Visitmgraphvertex (Graph->vertex[i]); EnQueue (&queue,i);//The current node subscript the queue//Why here to cycle out of the team. Out of the queue gets the subscript that has been visited over the node, and in the inner layer for continuing access to the associated junction point, the outer for loop is reduced to enter the IF number while (!
				Emptyqueue (&queue)) {int vexindex; DeQueue (&queue, &vexindex);//The node that is visited is marked out team for (int j = 0; J < graph->vertexnum; J + +) {//Connect the
				node and no visited node access, then Enqueue if (graph->edge[vexindex][j]! = 0 && G_visited[j] = = FALSE)	{G_visited[j] = TRUE;
						Visitmgraphvertex (Graph->vertex[j]);
					EnQueue (&queue, graph->vertex[j]);
}}}}} return;
	} int main (int argc, char *argv[]) {mgraph* mgraph = Createmgraph ();
	Printmgraph (mgraph);
	printf ("depth-first traversal adjacency matrix: \ n");
	Traversemgraph (mgraph);
	printf ("\ n breadth First traversal adjacency matrix: \ n");
	Bftmgraph (mgraph);
	printf ("\ n");
return 0;
 }

Code Run Detection

Let's create a diagram of the figure below, which is in the textbook.


Code Run Result:



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.