算法思想:使用深度优先遍历在图中搜索v到w的路径。在搜索时用数组来存储当前搜索的路径上的每一个顶点,如果路径符合要求,则将该路径顶点序列输出。
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX_VERTEX_NUM 100
typedef int VertexType;
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 vertices;
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.vertices[i].data = VList[i];
G.vertices[i].firstArc = NULL;
}
for (int i = 0; i < arcListLength; i++) {//注意for循环中i的遍历范围
int v = arcList[i][0];
int w = arcList[i][1];
ArcNode* pnode = (ArcNode*)malloc(sizeof(ArcNode));
pnode->adjVex = w;
pnode->nextArc = G.vertices[v].firstArc;
G.vertices[v].firstArc = pnode;
if (kind == 0) {
pnode = (ArcNode*)malloc(sizeof(ArcNode));
pnode->adjVex = v;
pnode->nextArc = G.vertices[w].firstArc;
G.vertices[w].firstArc = pnode;
}
}
G.arcNum = arcListLength;
G.vexNum = VListLength;
G.kind = kind;
}
int visited1[MAX_VERTEX_NUM] = { 0 };
void visit1(VertexType v) {
printf("%d ", v);
}
void DFS(ALGraph G, VertexType v) {
visit1(v);
visited1[v] = 1;
ArcNode* pnode = G.vertices[v].firstArc;
while (pnode != NULL) {
VertexType w = pnode->adjVex;
if (!visited1[w]) {
DFS(G, w);
}
pnode = pnode->nextArc;
}
}
void DFSTraves(ALGraph G) {
for (int index = 1; index <= G.vexNum; index++) {
if (visited1[index] == 0) {
DFS(G, index);
}
}
}
//得到所有v到w的简单路径
/*算法思想:使用深度优先遍历在图中搜索v到w的路径。在搜索时用数组来存储当前搜索的路径上的每一个顶点,如果路径符合要求,则将该路径顶点序列输出*/
int pathLength = 0;
VertexType path[MAX_VERTEX_NUM] = { 0 };
int visited2[MAX_VERTEX_NUM] = { 0 };
void print(VertexType* path, int pathLength) {
for (int i = 0; i < pathLength; i++) {
printf("%d ", path[i]);
}
printf("\n");
}
void DFSTraves(ALGraph G, VertexType v, VertexType w,int d) {
path[pathLength++] = v;
visited2[v] = 1;
if (v == w&&pathLength==d) {//v到w长度为d的路径
print(path, pathLength);
}
else {
ArcNode* pnode = G.vertices[v].firstArc;
while (pnode != NULL) {
VertexType k = pnode->adjVex;
if (visited2[k] == 0) {
DFSTraves(G, k, w,d);
}
pnode = pnode->nextArc;
}
}
visited2[v] = 0;//清除访问位,以免影响下一次入递归栈
path[--pathLength] = 0;//出递归站,结点出路径数组
}
void getPaths(ALGraph G,VertexType v,VertexType w,int d) {
DFSTraves(G, v, w,d);
}
int main() {
int kind, VListLength, arcListLength;
VertexType VList[MAX_VERTEX_NUM];
int arcList[MAX_VERTEX_NUM][2];
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);
ALGraph G;
createALGraph(G, VList, VListLength, arcList, arcListLength, kind);
//DFSTraves(G);
VertexType v, w;
int d;
scanf("%d %d %d", &v, &w,&d);//v到w长度为d的路径
getPaths(G, v, w,d);
}