这个是图的创建和查找路径,有什么问题可以一起交流,本人qq921064167,当然也可以私信或者评论区留言,有什么有难度的题也可以向我询问,虽然我也不一定会,ok.
#include<iostream>
#define maxsize 1024
using namespace std;
typedef struct _EdgeNode {
int weight;
char adjvex;
_EdgeNode* next;
}EdgeNode;
typedef struct _VertexNode {
char data;
_EdgeNode* first;
}VertexNode;
typedef struct _AdjListGraph {
VertexNode* adjlist;
int vex;
int edge;
}AdjListGraph;
bool visited[maxsize] = { 0 };
int Location(AdjListGraph& map,char c) {
for (int i = 0; i < map.vex; i++) {
if (map.adjlist[i].data == c) {
return i;
}
}
return -1;
}
bool initmap(AdjListGraph& map) {
map.adjlist = new VertexNode[maxsize];
map.edge = 0;
map.vex = 0;
for (int i = 0; i < maxsize; i++) {
visited[i] = false;
}
return true;
}
bool creatmap(AdjListGraph& map) {
cout << "请输入该图的顶点数以及边数:" << endl;
cin >> map.vex >> map.edge;
cout << "请输入相关顶点:" << endl;
for (int i = 0; i < map.vex; i++) {
cin >> map.adjlist[i].data;
map.adjlist[i].first = NULL;
}
cout << "请输入想关联边的顶点及权重:" << endl;
for (int i = 0; i < map.edge; i++) {
char a1 = 0;
char a2 = 0;
int weight=0;
cin >> a1 >> a2;
cin >> weight;
int q1 = Location(map, a1);
int q2 = Location(map, a2);
if (q1 == -1 || q2 == -1) {
cout << "找不到相关位置!" << endl;
return false;
}
_EdgeNode* node = new EdgeNode;
node->adjvex = a2;
node->weight = weight;
node->next = map.adjlist[q1].first;
map.adjlist[q1].first = node;
}
return true;
}
int path[maxsize] = { 0 };
int minpath[maxsize] = { 0 };
int min_weight = 0x7fffffff;
int step = 0;
void DFS(AdjListGraph& map,int start,int end,int weights) {
cout << "jinqu" << endl;
int cur = -1;
cur = start;
if (cur == end) {
cout << "jinqu=end" << endl;
for (int i = 0; i < step; i++) {
cout << map.adjlist[path[i]].data << " " << endl;
}
cout << "该路径对应的长度:" << weights << endl;
if (min_weight > weights) {
min_weight = weights;
memcpy(minpath, path, step * sizeof(int));
cout << "更新了一次最短路径" << endl;
}
}
visited[start] = true;
EdgeNode* edge = map.adjlist[cur].first;
cout << "kuai yao xun huan le " << endl;
while (edge) {
cout << "yunxing*********" << endl;
int weight = edge->weight;
cur = Location(map,edge->adjvex);
if (visited[cur] == false) {
visited[cur] = true;
path[step++] =cur;
DFS(map,cur, end, weights + weight);
visited[cur] = false;
path[--step] = 0;
}
edge = edge->next;
}
}
int main() {
AdjListGraph G;
initmap(G);
creatmap(G);
char start, end;
cout << "请输入要查询的最短路径的起点和终点:" << endl;
cin >> start >> end;
DFS(G, Location(G, start), Location(G, end), 0);
cout << "最小路径长度为:" <<min_weight << endl;
cout << "路径:";
int i = 0;
while (i < maxsize && minpath[i]>0) {
cout << G.adjlist[minpath[i]].data << " ";
i++;
}
cout << endl;
system("pause");
cout << "贼牛p" << endl;
}