Algorithm for constructing undirected graph based on adjacency matrix


Preface

  The adjacency matrix is ​​a commonly used data structure in graph theory to represent the graph structure, which can clearly represent the connection relationship between the nodes in the graph in the form of a matrix.

  This blog will discuss in depth the algorithm for constructing undirected graphs based on adjacency matrices and explore its implementation ideas.


1. Definition of adjacency matrix

  An adjacency matrix is ​​a two-dimensional array, usually represented as a square matrix. For an undirected graph, the size of its adjacency matrix is ​​n×n, where n is the number of nodes in the graph. The elements of the adjacency matrix can represent the connection relationship between nodes. The common representation is to use 0 and 1, where 1 represents that there is a connection between two nodes, and 0 represents that there is no connection.


2. Algorithm for constructing undirected graph based on adjacency matrix

#include <stdio.h>
#include <stdlib.h>
/*--------------邻接矩阵存储结构定义--------------*/
#define Maxsize 10
typedef struct
	{
    
    
		char Vex[Maxsize];			//顶点表
		int Edge[Maxsize][Maxsize];	//邻接矩阵,边表
		int vexnum,edgenum;			//记录顶点个数和边的条数
	}MGraph;

/*----------基于邻接矩阵构造无向图的算法----------*/
int LocateVex(MGraph &G,char v)
{
    
    //查找顶点v在顶点表中的下标
	for(int i=0;i<G.vexnum;i++)
		if(G.Vex[i]==v)
			return i;		//返回顶点v的下标
}

void CreateUndigraph(MGraph &G)
{
    
    
	printf("请输入总顶点数和总边数:");
	scanf("%d%d",&G.vexnum,&G.edgenum);
	getchar();//接收输入缓冲区的换行符
	for(int i=0;i<G.vexnum;i++)
	{
    
    
		printf("请输入第%d个顶点的信息:",i+1);
		scanf("%c",&G.Vex[i]);
		getchar();
	}
	for(int i=0;i<G.vexnum;i++)
	{
    
    //初始化邻接矩阵
		for(int j=0;j<G.vexnum;j++)
			G.Edge[i][j]=0;
	}
	for(int k=0;k<G.edgenum;k++)
	{
    
    
		char v1,v2;
		int i,j;
		printf("请输入第%d条边连接的两个顶点:",k+1);
		scanf("%c %c",&v1,&v2);
		getchar();
		i=LocateVex(G,v1);
		j=LocateVex(G,v2);
		G.Edge[i][j]=G.Edge[j][i]=1;
	}
}
/*---------------------------------------------*/

int main()
{
    
    
	MGraph G;
	CreateUndigraph(G);
	printf("邻接矩阵如下:\n");
	for(int i=0;i<G.vexnum;i++)
	{
    
    //输出邻接矩阵
		for(int j=0;j<G.vexnum;j++)
			printf("%d ",G.Edge[i][j]);
		putchar('\n');
	}
	system("pause");
}

The running results are as follows:
Insert image description here


Summarize

  The algorithm for constructing undirected graphs based on adjacency matrices uses two-dimensional arrays to clearly represent the connection relationships between nodes in the graph. This algorithm has a wide range of applications in practical applications, such as graph traversal, shortest path, etc. Understanding the construction algorithm of adjacency matrices is critical to dealing with graph theory problems, and helps us better understand and analyze the properties and behavior of graph structures.

Guess you like

Origin blog.csdn.net/qq_43341612/article/details/129504121