算法思想:对图进行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);
}
}
测试结果如下: