#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
typedef struct Graph
{
char* vertex;
char* edge;
size_t vexnum;
}Graph;
Graph* create_graph(char* str)
{
// 申请图所需要的存储空间
Graph* graph = malloc(sizeof(Graph));
// 备份顶点的数量
graph->vexnum = strlen(str);
// 给顶点表分配存储空间
graph->vertex = malloc(graph->vexnum);
// 备份顶点
strncpy(graph->vertex,str,graph->vexnum);
// 给边表分配存储空间
graph->edge = calloc(graph->vexnum,graph->vexnum);
return graph;
}
int vertex_index(Graph* graph,char v)
{
for(int i=0; i<graph->vexnum; i++)
{
if(graph->vertex[i] == v)
return i;
}
return -1;
}
bool add_edge(Graph* graph,char v1,char v2)
{
int index1 = vertex_index(graph,v1);
int index2 = vertex_index(graph,v2);
if(index1 < 0 || index2 < 0 || index1==index2)
return false;
graph->edge[graph->vexnum*index2+index1] = 1;
}
void show_edge(Graph* graph)
{
for(int i=0; i<graph->vexnum; i++)
{
for(int j=0; j<graph->vexnum; j++)
{
printf("%d ",graph->edge[i*graph->vexnum+j]);
}
printf("\n");
}
}
size_t vertex_out(Graph* graph,char v)
{
int index = vertex_index(graph,v);
if(0 > index)
return -1;
size_t degree = 0;
for(int i=0; i<graph->vexnum; i++)
{
degree += graph->edge[i*graph->vexnum+index];
}
return degree;
}
size_t vertex_in(Graph* graph,char v)
{
int index = vertex_index(graph,v);
if(0 > index)
return -1;
size_t degree = 0;
for(int i=0; i<graph->vexnum; i++)
{
degree += graph->edge[graph->vexnum*index+i];
}
return degree;
}
void _dfs(Graph* graph,int index,bool flags[])
{
printf("%c ",graph->vertex[index]);
flags[index] = true;
for(int i=0; i<graph->vexnum; i++)
{
if(graph->edge[graph->vexnum*i+index] && !flags[i])
{
_dfs(graph,i,flags);
}
}
}
void dfs_graph(Graph* graph)
{
// 给每个顶点定义访问标记数组并初始化
bool flags[graph->vexnum];
bzero(flags,graph->vexnum);
for(int i=0; i<graph->vexnum; i++)
{
if(!flags[i])
_dfs(graph,i,flags);
}
printf("\n");
}
void bfs_graph(Graph* graph)
{
// 给每个顶点定义访问标记数组并初始化
bool flags[graph->vexnum];
bzero(flags,graph->vexnum);
int queue[graph->vexnum] , front = 0 , rear = 0;
for(int i=0; i<graph->vexnum; i++)
{
if(!flags[i])
queue[rear++] = i;
while(front != rear)
{
int index = queue[front++];
flags[index] = true;
printf("%c ",graph->vertex[index]);
for(int j=0; j<graph->vexnum; j++)
{
if(graph->edge[graph->vexnum*j+index] && !flags[j])
{
queue[rear++] = j;
}
}
}
}
printf("\n");
}
int main(int argc,const char* argv[])
{
char* str = "ABCDEFG";
Graph* graph = create_graph(str);
add_edge(graph,'A','C');
add_edge(graph,'A','G');
add_edge(graph,'C','D');
add_edge(graph,'G','F');
add_edge(graph,'G','E');
show_edge(graph);
bfs_graph(graph);
}
【数据结构与算法】用图的邻接矩阵来遍历
最新推荐文章于 2024-07-23 22:06:37 发布