#include <stdio.h>
#include <stdlib.h>
#define MAXVEX 20
typedef int VertexType;
typedef struct EdgeNode{
int adjvex;
struct EdgeNode *next;
}EdgeNode;
typedef struct VertexNode{
VertexType data;
EdgeNode *firstedge;
}VertexNode,AdjList[MAXVEX];
typedef struct{
AdjList adjlist;
int numVertexes,numEdges;
}GraphAdjList;
void Create(GraphAdjList *G){
int i,j,k;
EdgeNode *p;
printf("输入顶点数和边数:\n");
scanf("%d%d",&G->numVertexes,&G->numEdges);
printf("输入顶点信息:\n");
for(i=0;i<G->numVertexes;i++){
scanf("%d",&G->adjlist[i].data);
G->adjlist[i].firstedge=NULL;
}
printf("输入边(Vi,Vj)中的下标i,j:\n");
for(k=0;k<G->numEdges;k++){
scanf("%d%d",&i,&j);
p=(EdgeNode *)malloc(sizeof(EdgeNode));
p->adjvex=j;
p->next=G->adjlist[i].firstedge;
G->adjlist[i].firstedge=p;
}
printf("邻接表为:\n");
for(i=0;i<G->numVertexes;i++){
p=G->adjlist[i].firstedge;
while(p){
printf("(%d,%d)",G->adjlist[i].data,G->adjlist[p->adjvex].data);
p=p->next;
}
printf("\n");
}
}
int visited[MAXVEX]={0};
void FindPath(GraphAdjList *G,int u,int v,int path[],int d)
{
int w,i;
EdgeNode *p;
d++;
path[d]=u;
visited[u]=1;
if(u==v)
{
for(i=0;i<=d;i++)
printf("%2d",path[i]);
printf("\n");
}
p=G->adjlist[u].firstedge;
while(p!=NULL)
{
w=p->adjvex;
if(visited[w]==0)
FindPath(G,w,v,path,d);
p=p->next;
}
visited[u]=0;
}
void PathAll(GraphAdjList *G,int u,int v,int l,int path[],int d)
{
int w,i;
EdgeNode *p;
d++;
path[d]=u;
visited[u]=1;
if(u==v && d==l)
{
for(i=0;i<=d;i++)
printf("%2d",path[i]);
printf("\n");
}
p=G->adjlist[u].firstedge;
while(p!=NULL)
{
w=p->adjvex;
if(visited[w]==0)
PathAll(G,w,v,l,path,d);
p=p->next;
}
visited[u]=0;
}
void CyclePath(GraphAdjList *G,int u,int v,int path[],int d)
{
int w,i;
EdgeNode *p;
visited[u]=1;
d++;
path[d]=u;
p=G->adjlist[u].firstedge;
while(p!=NULL)
{
w=p->adjvex;
if(visited[w]==0)
CyclePath(G,w,v,path,d);
else if(w==v && d>0)
{
for(i=0;i<=d;i++)
printf("%2d",path[i]);
printf("%2d\n",v);
}
p=p->next;
}
visited[u]=0;d--;
}
void CycleAll(GraphAdjList *G,int u)
{
int path[MAXVEX];
printf("经过%d顶点的所有回路如下:\n",u);
CyclePath(G,u,u,path,-1);
}
int main(){
freopen("in.txt","r",stdin);
GraphAdjList G;
Create(&G);
int path[MAXVEX],u=0,v=4;
GraphAdjList *G1 = &G;
CycleAll(G1,0);
}