给定一个有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.
输入样例2:
7 6
0 1
2 3
1 4
0 2
1 3
5 6
0 6
输出样例2:
There is no path between 0 and 6.
#include<iostream>
using namespace std;
#define MVNum 100 //最大顶点数
typedef struct
{
char vexs[MVNum]; //存放顶点的一维数组
int arcs[MVNum][MVNum]; //邻接矩阵
int vexnum,arcnum; //图的当前顶点数和边数
}MGraph;
void CreatMGraph(MGraph *G);/* 创建图 */
int IF(MGraph *G,int a,int b);
int main()
{
MGraph G;
CreatMGraph(&G);
int m,n;
cin>>m>>n;
if(IF(&G,m,n)==1)
cout<<"There is a path between "<<m<<" "<<"and "<<n<<".";
else
cout<<"There is no path between "<<m<<" "<<"and "<<n<<".";
return 0;
}
int IF(MGraph *G,int a,int b)
{
int temp;
int i,j,k;
if(a==b)
return 1;
if(G->arcs[a][b]==1)
return 1;
else if(G->arcs[b][a]==1)
return 1;
else
for(j=0;j<G->vexnum;j++)
{
if(G->arcs[a][j]==1)
{
temp=IF(G,j,b);
if(temp==1)
return 1;
}
else if(G->arcs[j][a]==1)
{
temp=IF(G,b,j);
if(temp==1)
return 1;
}
}
return 0;
}
void CreatMGraph(MGraph *G)
{
int i;
int j=0;
int k=0;
char a;
cin>>G->vexnum>>G->arcnum;
getchar();
for(i=0;i<G->vexnum;i++)
for(j=0;j<G->vexnum;j++)
G->arcs[i][j]=0;
for(i=0;i<G->arcnum;i++)
{
cin>>j>>k;
getchar();
G->arcs[j][k]=1;
}
}
从这道题真的可以看出PTA出题以及检测功能完善的有多么的好了。
1.首先这道题是无向图,所以0 1或者1 0都能说明顶点1和顶点0之间存在路径
2.其次测试中包含了0 0这种顶点自身到自身的情况,应该特别说明
3.最后我有一个测试点一直没过 如果有大佬知道是哪儿出了问题 还请指正 感激不尽。