PTA-路径探索

给定一个有N个顶点和E条边的无向图,请判断给定的两个顶点之间是否有路径存在。 假设顶点从0到N−1编号。

**

输入格式:

**
输入第1行给出2个整数N(0

随后E行,每行给出一条边的两个端点。每行中的数字之间用1空格分隔。

最后一行给出两个顶点编号i,j(0≤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 
#define MVnum 10
typedef struct
{
	int vexs[MVnum];//顶点表
	int arcs[MVnum][MVnum];//邻接矩阵
	int vexsnum, arcnum;//顶点数,边数
}AMGraph;
//定义一个全局变量,记录是否经过这个点
int visited[MVnum];
//创建图
void CreateGraph(AMGraph *G)
{
	int i = 0,j=0,k=0;
	scanf("%d %d", &G->vexsnum, &G->arcnum);
	getchar();
	for (i = 0; i < G->vexsnum; i++)
	{
		G->vexs[i] = i;
	}
	//初始化矩阵
	for (i = 0; i < G->vexsnum; i++)
	{
		for (j = 0; j < G->vexsnum; j++)
		{
			G->arcs[i][j] = 0;
		}
	}
	//构造矩阵
	for (k = 0; k < G->arcnum; k++)
	{
		scanf("%d %d", &i, &j);
		G->arcs[i][j] = 1;
		G->arcs[j][i] = 1;
	}
}
//深度优先遍历
void DFS(AMGraph G, int v)
{
	int w = 0;
	visited[v] = 1;
	for (w = 0; w < G.vexsnum; w++)
	{
		if (G.arcs[v][w] == 1 && visited[w] == 0)
		{
			DFS(G, w);
		}
	}
}
//路径判断
void pathjuge(AMGraph G)
{
	int i, j,k;
	scanf("%d %d", &i, &j);
	//先将数组初始化为0
	for (k = 0; k < G.vexsnum; k++)
	{
		visited[k] = 0;
	}
	DFS(G, i);
	//如果visited[j]==1,则说明遍历到j了,说明i,j之间有路径
	if (visited[j] == 1)
	{
		printf("There is a path between %d and %d.", i, j);
	}
	else
		printf("There is no path between %d and %d.", i, j);
}
int main()
{
	AMGraph M;
	CreateGraph(&M);
	pathjuge(M);
	return 0;
}

你可能感兴趣的:(PTA-路径探索)