题目描述:
已知一个有向图g已经建立,求从该图的某个顶点出发,经过两条边所能到达的顶点的集合。例如从顶点M出发,经过一条边到达顶点N,再经过一条边到达顶点T,则顶点T属于该集合,而顶点N不属于该集合。(该图的存储方式可以是邻接矩阵或邻接表,可以根据需要任意选用。)
#include "stdio.h"
#include "stdlib.h"
#include "math.h"
#define MAXVEX 100 /* 最大顶点数,应由用户定义 */
typedef int Status;
typedef char VertexType;
typedef int InfoType;
int m;
int res[MAXVEX],dist[MAXVEX],num;
int vis[MAXVEX];
typedef struct ArcNode /* 边表结点 */
{
int adjvex; /* 邻接点域,存储该顶点对应的下标 */
InfoType info; /* 用于存储权值,对于非网图可以不需要 */
struct ArcNode *next; /* 链域,指向下一个邻接点 */
}ArcNode;
typedef struct VexNode /* 顶点表结点 */
{
VertexType data; /* 顶点域,存储顶点信息 */
ArcNode *firstedge;/* 边表头指针 */
}VexNode, AdjList[MAXVEX];
typedef struct
{
AdjList adjList;
int vexnum,arcnum; /* 图中当前顶点数和边数 */
}ALGraph;
ALGraph G;
/* 建立图的邻接表结构 */
void CreateALGraph(ALGraph *G)
{
int i,j,k;
ArcNode *e;
printf("输入顶点数和边数:\n");
scanf("%d %d",&G->vexnum,&G->arcnum); /* 输入顶点数和边数 */
for(i = 0;i < G->vexnum;i++) /* 建立顶点表 */
{
// scanf(&G->adjList[i].data);
G->adjList[i].data=i;
G->adjList[i].firstedge=NULL; /* 将边表置为空表 */
}
printf("输入边(vi,vj)上的顶点序号:\n");
for(k = 0;k < G->arcnum;k++)/* 建立边表 */
{
scanf("%d %d",&i,&j); /* 输入边(vi vj)上的顶点序号 */
e=(ArcNode *)malloc(sizeof(ArcNode)); /* 向内存申请空间,生成边表结点 */
e->adjvex=j; /* 邻接序号为j */
e->next=G->adjList[i].firstedge; /* 将e的指针指向当前顶点上指向的结点 */
G->adjList[i].firstedge=e; /* 将当前顶点的指针指向e */
}
}
void check()
{
scanf("%d",&m); /* 输入索要查询的顶点M */
m--;
ArcNode *t;
for(t=G.adjList[m].firstedge;t!=NULL;t=t->next)
{
int tmp=t->adjvex;
ArcNode *p;
for(p=G.adjList[tmp].firstedge;p!=NULL;p=p->next)
{
int k=p->adjvex;
if(vis[k]==0)
{
res[num++]=k;
vis[k]=1;
}
}
}
}
int main()
{
CreateALGraph(&G);
check();
for(int i=0;i<num;i++)
printf("%d ",res[i]);
return 0;
}
/*
5 7
1 2
2 3
3 5
3 4
1 3
2 4
4 5
2
4 5 3
*/