网上大多是二维矩阵和循环算法,本篇则是基于邻接表的递归算法求图的回路和通路。
代码如下:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ok 1
#define error 0
#define max 255
typedef char elemtype;
int cnt[5] = { 0 };
int count[5] = { 0 };
int num[max] = { 0 };
typedef struct arcnode
{
int adjvex;
struct arcnode* nextarc;
}arcnode;
typedef struct vnode
{
elemtype data;
arcnode* fistarc;
}vnode, adjlist[max];
typedef struct algraph
{
int vexnum, arcnum;
adjlist a;
}algraph;
int locatevex(algraph g, elemtype c)
{
for (int i = 0;i < g.vexnum;i++)
{
if (g.a[i].data == c)return i;
}
return error;
}
void creategraph(algraph* g)
{
printf("请输入顶点个数和边数\n");
scanf("%d%d", &g->vexnum, &g->arcnum);
printf("请输入顶点值");
printf("\n");
getchar();
for (int i = 0;i < g->vexnum;i++)
{
scanf("%c", &g->a[i].data);
g->a[i].fistarc = NULL;
}
getchar();
printf("请输入顶点队\n");
for (int i = 0;i < g->arcnum;i++)
{
char v1;
char v2;
scanf("%c %c", &v1, &v2);
int j = locatevex(*g, v1);
int k = locatevex(*g, v2);
arcnode* p1 = (arcnode*)malloc(sizeof(arcnode));
arcnode* p2 = (arcnode*)malloc(sizeof(arcnode));
p1->adjvex = k;
p1->nextarc = g->a[j].fistarc;
g->a[j].fistarc = p1;
/*p2->adjvex= j;
* p2->nextarc=g->a[k].firstarc;
* g->a[k],firstarc=p2;
*///针对无向图
getchar();
}
}
void get_num(algraph g)
{
for (int i = 0;i < g.vexnum;i++)
{
int count = 0;
arcnode* p = g.a[i].fistarc;
while (p!=NULL)
{
p = p->nextarc;
count++;
}
num[i] = count;
}
}
void dgcnt(algraph g,int i,int k,elemtype ch)
{
if (k == 5)return;
arcnode* p = g.a[i].fistarc;
while (p!=NULL)
{
int n = p->adjvex;
if (g.a[n].data == ch)cnt[k]++;
dgcnt(g, n, k + 1,ch);
p = p->nextarc;
}
}
void dgcount(algraph g, int i,int k)
{
if (k == 5)return;
arcnode* p = g.a[i].fistarc;
count[k] += num[i];
while (p != NULL)
{
int n = p->adjvex;
dgcount(g, n, k + 1);
p = p->nextarc;
}
}
void pd(algraph g)
{
for (int i = 0;i < g.vexnum;i++)
{
int k = i;
arcnode* p = g.a[i].fistarc;
elemtype ch = g.a[i].data;
dgcount(g, i, 1);
dgcnt(g, i, 1, ch);
}
for (int i = 1;i <= 4;i++)
{
printf("长度%d的通路有%d条\n",i,count[i]);
printf("其中回路有%d条\n",cnt[i]);
}
printf("长度小于4的通路有%d条\n", count[1] + count[2] + count[3] + count[4]);
printf("其中回路有%d条\n", cnt[1] + cnt[2] + cnt[3] + cnt[4]);
}
int main()
{
algraph g;
creategraph(&g);
get_num(g);
pd(g);
}
运行结果:
标签:fistarc,递归,vexnum,int,离散数学,++,algraph,arcnode,求图 From: https://blog.csdn.net/2302_80475491/article/details/139357055