对于给定的无向图及两个图中的顶点,请实现一个函数,分别打印包含这两个顶点的连通分量中的顶点数,并判断这两个顶点之间是否有路径。
函数接口定义:
int hasPath(struct Graph *g, int v, int w);
其中v
和w
是顶点
图定义如下:
#define MaxVertexNum 20 /* 最大顶点数 */
struct Graph{
int v; /* 顶点数量 */
int Adj[MaxVertexNum][MaxVertexNum]; /* 邻接矩阵 */
};
题目保证图至少有一个顶点
函数分别在第一行和第二行打印包含v
和w
的连通分量中顶点的数量。
如果 v
和w
之间有路径,函数返回1
, 否则返回0
.
提示:
- 你可以定义多个函数,也可以定义全局变量.
- 当
v
和w
是同一个顶点时,认为v
和w
之间是有路径的。
裁判测试程序样例:
#include <stdio.h>
#include <stdlib.h>
#define MaxVertexNum 20 /* 最大顶点数设为20 */
struct Graph{
int v; // amount of vertices
int Adj[MaxVertexNum][MaxVertexNum]; /* 邻接矩阵 */
};
int visited[MaxVertexNum]; /* 顶点的访问标记 */
struct Graph* CreateGraph(){
int v;
scanf("%d",&v);
struct Graph* g;
g = malloc(sizeof(struct Graph));
if(!g) return NULL;
g->v = v;
for(int i=0; i<v; i++){
visited[i] = 0;
for(int j=0; j<v; j++)
scanf("%d",&(g->Adj[i][j]));
}
return g;
}
int hasPath(struct Graph *g, int v, int w);
int main(){
struct Graph* g;
g = CreateGraph();
int v,w;
scanf("%d%d", &v, &w);
printf("%s\n", hasPath(g,v,w) ? "Yes" : "No");
return 0;
}
/* 你的代码将被嵌在这里 */
对于此图及样例测试程序规定的输入格式:
8
0 1 1 0 0 0 0 1
1 0 0 0 1 0 0 0
1 0 0 0 1 0 0 0
0 0 0 0 0 1 0 0
0 1 1 0 0 0 0 0
0 0 0 1 0 0 0 0
0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0
1 3
Sample Output:
5
2
No
//int vsited[MaxVertexNum];
int vlt[MaxVertexNum];
int wlt[MaxVertexNum];
void DFSv(struct Graph* G,int v){
int i=0;
//visited[v]=1;
vlt[v]=1;
for(i=0;i<G->v;i++){
if(G->Adj[v][i]==1&&vlt[i]==0)DFSv(G,i);
}
}
void DFSw(struct Graph* G,int w){
int i=0;
//visited[v]=1;
wlt[w]=1;
for(i=0;i<G->v;i++){
if(G->Adj[w][i]==1&&wlt[i]==0)DFSw(G,i);
}
}
int hasPath(struct Graph *g, int v, int w){
DFSv(g,v);
DFSw(g,w);
int vnum=0;
int wnum=0;
int i=0;
for(i=0;i<g->v;i++){
if(vlt[i]==1)vnum++;
}
for(i=0;i<g->v;i++){
if(wlt[i]==1)wnum++;
}
printf("%d\n%d\n",vnum,wnum);
int flag=0;
if(vlt[w]==1||w==v)flag=1;
return flag;
}