判断是否存在v到w的路径

算法思想:对图进行DFS遍历算法,如果在遍历过程中访问到了w结点,则表示存在v到w的路径;否则,则不存在v到w的路径。

图例如下:

完整代码如下: 

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef int VertexType;
#define MAX_VERTEX_NUM 100
//弧结点
typedef struct ArcNode {
	int adjvex;//临界域
	struct ArcNode* nextArc;
	int weight;
}ArcNode;
//头结点
typedef struct VNode {
	VertexType data;
	ArcNode* firstArc;
}VNode,AdjList[MAX_VERTEX_NUM];
//图
typedef struct {
	AdjList veryices;
	int arcNum, vexNum;
	int kind;
}ALGraph;
//建图
void createALGraph(ALGraph &G,VertexType VList[], int VListLength, int arcList[][2], int arcListLength, int kind) {
	for (int i = 1; i <= VListLength; i++) {
		G.veryices[i].data = VList[i];
		G.veryices[i].firstArc = NULL;
	}
	for (int i = 0; i < arcListLength; i++) {
		int v = arcList[i][0];
		int w = arcList[i][1];
		ArcNode* pnode = (ArcNode*)malloc(sizeof(ArcNode));
		pnode->adjvex = w;
		pnode->nextArc = G.veryices[v].firstArc;
		G.veryices[v].firstArc = pnode;
		if (kind == 0) {
			pnode = (ArcNode*)malloc(sizeof(ArcNode));
			pnode->adjvex = v;
			pnode->nextArc = G.veryices[w].firstArc;
			G.veryices[w].firstArc = pnode;
		}
	}
	G.vexNum= VListLength;
	G.arcNum = arcListLength;
	G.kind = kind;
}
//DFS遍历图
int visited1[MAX_VERTEX_NUM] = { 0 };
void visit(VertexType v) {
	printf("%d ", v);
}
void DFS(ALGraph G, VertexType v) {
	visit(v);
	visited1[v] = 1;
	ArcNode* pnode = G.veryices[v].firstArc;
	while (pnode != NULL) {
		v = pnode->adjvex;
		if (!visited1[v]) {
			DFS(G,v);
		}
		pnode = pnode->nextArc;
	}
}
void DFSTraves(ALGraph G) {
	for (int i = 1; i <= G.vexNum; i++) {
		if (!visited1[i]) {
			DFS(G, i);
		}
	}
}
//判断是否存在v到w的路径
int visited[MAX_VERTEX_NUM] = { 0 };
int ret = 0;//存在标记位
int isExistedPath(ALGraph G, VertexType v, VertexType w) {//从v开始搜索到w的路径
	if (v == w) {
		ret = 1;
	}
	visited[v] = 1;
	ArcNode* pnode = G.veryices[v].firstArc;
	while (pnode != NULL) {
		v = pnode->adjvex;
		int ret = 0;
		if (!visited[v]) {
			isExistedPath(G, v,w);
		}
		pnode = pnode->nextArc;
	}
	return ret;//遍历程序结束的位置
}
int main() {
	ALGraph G;
	VertexType VList[MAX_VERTEX_NUM];
	int VListLength;
	int arcList[MAX_VERTEX_NUM][2];
	int arcListLength;
	int kind;
	scanf("%d", &VListLength);
	for (int i = 1; i <= VListLength; i++) {
		scanf("%d", &VList[i]);
	}
	scanf("%d", &arcListLength);
	for (int i = 0; i < arcListLength; i++) {
		for (int j = 0; j < 2; j++) {
			scanf("%d", &arcList[i][j]);
		}
	}
	scanf("%d", &kind);
	createALGraph(G,VList, VListLength, arcList, arcListLength, kind);
	//DFSTraves(G);
	VertexType v;
	VertexType w;
	scanf("%d %d", &v, &w);
	if (isExistedPath(G, v, w)) {
		printf("存在%d到%d的路径\n", v, w);
	}
	else {
		printf("不存在%d到%d的路径\n", v, w);
	}
}

测试结果如下:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值