函数实现:
int pathnum = 0;
int path[MaxSize];
int j = 0;
int start;
void findcircle(ALGraph* G, int v1)
{
EdgeNode* p;
if(pathnum == 0)
start = v1;
int nextadj;
path[j++] = v1;
visited[v1] = 1;
p = G->adjlist[v1].firstarc;
while (p!=NULL)
{
nextadj = p->dest;
if (nextadj == start && pathnum > 2)//成环了
{
for (int i = 0; i < j; i++)
printf("%c ", G->adjlist[path[i]].VertexName);
printf("%c\n", G->adjlist[start].VertexName);
}
else if(!visited[nextadj])//没有成环
{
pathnum++;
findcircle(G, nextadj);
j--;
pathnum--;
if (pathnum > 0)
visited[nextadj] = 0;
}
p = p->next;
}
}
全部代码:
#include <stdlib.h>
#include <stdio.h>
#include<conio.h>
#define MaxVerNum 100
#define MaxSize 100
int visited[MaxSize];
typedef struct enode //边的节点结构类型
{
int dest;//终点
struct enode* next;
}EdgeNode;
typedef struct VertexNode //头结点结构类型
{
char VertexName;
EdgeNode* firstarc;
}VERTEXNODE;
typedef struct
{
VERTEXNODE adjlist[MaxVerNum];
int n, e;//n-顶点,e-边
}ALGraph;
ALGraph g1;
ALGraph* CreateGraphList(ALGraph* g)
{
int i, k, w, v;
int n, e;
EdgeNode* p;
g = (ALGraph*)malloc(sizeof(ALGraph));
printf("请输入有向图的顶点与边:");
scanf_s("%d,%d", &n, &e);
g->n = n;
g->e = e;
for (i = 0; i < n; i++)//头结点初始化
g->adjlist[i].firstarc = NULL;
printf("请输入%d个顶点:\n", n);
for (i = -1; i < n; i++)
scanf_s("%c", &g->adjlist[i].VertexName, 20);
for (i = 0; i < e; i++)
{
printf("请输入第%d条边:", i + 1);
scanf_s("%d,%d", &k, &w);
EdgeNode* newnode;
//有向图的建立
newnode = (EdgeNode*)malloc(sizeof(EdgeNode));
newnode->dest = w;
newnode->next = g->adjlist[k].firstarc;
g->adjlist[k].firstarc = newnode;
newnode = (EdgeNode*)malloc(sizeof(EdgeNode));
newnode->dest = k;
newnode->next = g->adjlist[w].firstarc;
g->adjlist[w].firstarc = newnode;
}
return g;
}
int pathnum = 0;
int path[MaxSize];
int j = 0;
int start;
void findcircle(ALGraph* G, int v1)
{
EdgeNode* p;
if(pathnum == 0)
start = v1;
int nextadj;
path[j++] = v1;
visited[v1] = 1;
p = G->adjlist[v1].firstarc;
while (p!=NULL)
{
nextadj = p->dest;
if (nextadj == start && pathnum > 2)//成环了
{
for (int i = 0; i < j; i++)
printf("%c ", G->adjlist[path[i]].VertexName);
printf("%c\n", G->adjlist[start].VertexName);
}
else if(!visited[nextadj])//没有成环
{
pathnum++;
findcircle(G, nextadj);
j--;
pathnum--;
if (pathnum > 0)
visited[nextadj] = 0;
}
p = p->next;
}
}
int main()
{
ALGraph* g = &g1;
g = CreateGraphList(g);
for (int i = 0; i < g->n; i++)
visited[i] = 0;
int x;
printf("请输入简单回路的起始点:");
scanf_s("%d", &x);
printf("简单回路:\n");
for (int i = 0; i < g->n; i++)
visited[i] = 0;
findcircle(g,x);
return 1;
}