#include <bits/stdc++.h>
#include "Graph.cpp"
using namespace std;
int visited[MAXV];
void FindaPath(ALGraph *G, int u, int v, vector<int> apath, vector<int> &path){
int w;
ArcNode *p;
visited[u] = 1;
apath.push_back(u);
if(u == v){
path = apath;
return;
}
p = G->adjlist[u].firstarc; // p指向顶点u的第一个相邻点
while(p != NULL){
w = p->adjvex;
if(visited[w] == 0)
FindaPath(G, w, v, apath, path);
p = p->nextarc;
}
}
int main(){
ALGraph *G;
int A[][MAXV] ={
{0,1,0,0,1},
{0,0,1,1,1},
{0,0,0,0,0},
{0,0,1,0,1},
{0,0,0,0,0}
};
int n = 5, e = 7;
CreateAdj(G, A, n, e);
cout << "图的邻接表如下:" << endl;
DispAdj(G);
vector<int> apath, path;
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
if(i != j){
memset(visited,0,sizeof(visited));
path.clear();
FindaPath(G, i, j, apath, path);
if(path.size() > 0){
cout << "顶点" << i << "到顶点" << j << "的简单路径:";
for(int k = 0; k < path.size(); k++)
cout << path[k] << " ";
cout << endl;
}
}
return 0;
}
#include <bits/stdc++.h>
#define MAXV 50 // 最大顶点个数
#define MAXL 20
#define INF 0x3f3f3f3f //表示∞
using namespace std;
typedef struct ANode {
int adjvex; // 该边的终点编号
int weight; // 改变的权值
struct ANode *nextarc; //指向下一条边的指针
} ArcNode; // 边结点的类型
typedef struct Vnode {
char data[MAXL]; // 顶点信息
ArcNode *firstarc; // 指向第一条边
} VNode; // 邻接表的表头的结点类型
typedef VNode AdjList[MAXV]; // AdjList是邻接表类型
typedef struct {
AdjList adjlist; // 邻接表
int n, e; // 图中的顶点数和边数
} ALGraph; // 图
void CreateAdj(ALGraph *&G, int A[][MAXV], int n, int e) { //建立图的邻接表
ArcNode *p;
G = (ALGraph *) malloc (sizeof(ALGraph));
G->n = n;
G->e = e;
for(int k = 0; k < n; k++)
G->adjlist[k].firstarc = NULL;
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
if(A[i][j] != 0 && A[i][j] != INF) {
p = (ArcNode *) malloc (sizeof(ArcNode));
p->adjvex = j;
p->weight = A[i][j];
p->nextarc = G->adjlist[i].firstarc;
G->adjlist[i].firstarc = p;
}
}
void DispAdj(ALGraph *G) {
ArcNode *p;
for(int i = 0; i < G->n; i++) {
cout << i;
p = G->adjlist[i].firstarc;
while(p != NULL) {
cout << "->" << "结点编号:" << p->adjvex << " 边的权值:" << p->weight;
p = p->nextarc;
}
cout << "^" << endl;
}
}
void DestroyAdj(ALGraph *&G) { // 销毁图的邻接表
ArcNode * pre ,*p;
for(int i = 0; i < G->n; i++) {
pre = G->adjlist[i].firstarc;
while(pre != NULL) {
p = pre->nextarc;
free(pre);
pre = p;
}
}
free(G);
}
因篇幅问题不能全部显示,请点此查看更多更全内容
Copyright © 2019- awee.cn 版权所有 湘ICP备2023022495号-5
违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务