#include<bits/stdc++.h>
using namespace std;
#define max 1001
typedef struct {
int data[max][max];
int vex;
int arm;
}*graph,Graph;//定义图
void creatgp(graph &p)
{
if(p==NULL)
{
p=new Graph;
cin>>p->vex>>p->arm;
for(int i=0;i<max;i++)
{
for(int j=0;j<max;j++)
{
p->data[i][j]=0;
}
}
for(int i=0;i<p->arm;i++)
{
int a,b;
cin>>a>>b;
p->data[a][b]=1;
p->data[b][a]=1;
}
}
}
void dfs(graph p,int n,int *visit)
{
visit[n]=1;
for(int i=0;i<p->vex;i++)
{
int o = p->data[n][i];
if(visit[i]==0&&o==1)
{
dfs(p,i,visit);
}
}
}
int main()
{
graph p=NULL;
creatgp(p);
int a[max]={0};//访问数组
int n,m;
cin>>n>>m;
dfs(p,n,a);//从初始开始搜索
if(a[m])
{
cout<<"There is a path between "<<n<<" and "<<m<<".";
}
else{
cout<<"There is no path between "<<n<<" and "<<m<<".";
}
return 0;
}
给定一个有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.