给定一个有N个顶点和E条边的无向图,请判断给定的两个顶点之间是否有路径存在。 假设顶点从0到N−1编号。
输入格式:
输入第1行给出2个整数N(0<N≤10)和E,分别是图的顶点数和边数。
随后E行,每行给出一条边的两个端点。每行中的数字之间用1空格分隔。
最后一行给出两个顶点编号i,j(0≤i,j<N),i和j之间用空格分隔。
输出格式:
如果i和j之间存在路径,则输出"There is a path between i and j.",
否则输出"There is no path between i and j."。
输入样例1:
7 6
0 1
2 3
1 4
0 2
1 3
5 6
0 3
输出样例1:
There is a path between 0 and 3.
思路:用图的遍历算法从 i 遍历一遍图,看 j 是否访问过,若是则 i 和 j 存在路径,反之则无。
#include<stdio.h>
#include<stdlib.h>
#define MaxVertexNum 10 /* 最大顶点数设为10 */
typedef struct GNode *PtrToGNode;
struct GNode{
int Nv; /* 顶点数 */
int Ne; /* 边数 */
int g[MaxVertexNum][MaxVertexNum]; /* 邻接矩阵 */
};
typedef PtrToGNode MGraph; /* 以邻接矩阵存储的图类型 */
int isvisited[20];
void DFS( MGraph Graph, int V)
{
isvisited[V] = 1;
for(int j=0;j<Graph->Nv;j++)
{
int w = Graph->g[V][j];
if(w != 0 && !isvisited[j])
{
DFS(Graph,j);
}
}
}
int main()
{
PtrToGNode G = (PtrToGNode)malloc(sizeof(struct GNode));
scanf("%d %d",&G->Nv,&G->Ne);
int x,y;
for(int i=0;i<G->Nv;i++)
{
isvisited[i] = 0;
for(int j=0;j<G->Nv;j++)
{
G->g[i][j] = 0;
}
}
for(int i=0;i<G->Ne;i++)
{
scanf("%d %d",&x,&y);
G->g[x][y] = 1;
G->g[y][x] = 1;
}
scanf("%d %d",&x,&y);
DFS(G,x);
if(isvisited[y] == 1)
{
printf("There is a path between %d and %d.",x,y);
}
else
{
printf("There is no path between %d and %d.",x,y);
}
return 0;
}