#include<iostream>
#include<queue>
#include<string.h>
using namespace std;
typedef struct ArcNode {
int adjvex;
struct ArcNode* nextArc;
}ArcNode; //边节点
typedef struct VNode {
int data;
ArcNode* firstArc;
}VNode, * AdjList;
typedef struct {
int vNum, arcNum;
AdjList vertices;
}ALGraph;
int LocateVNode(ALGraph g, int index) {
int flag = 0;
for (int i = 0; i < g.vNum; i++) {
if (g.vertices[i].data==index) {
flag = 1;
return i;
}
}
if (flag == 0) {
return -1;//查找失败
}
}
int CreateUDG(ALGraph& g) {
cin >> g.vNum >> g.arcNum;
g.vertices = new VNode[g.vNum];
for (int i = 0; i < g.vNum; i++) {
cin >> g.vertices[i].data;
g.vertices[i].firstArc = NULL;
}
for (int i = 0; i < g.arcNum; i++) {
int v1, v2;
cin >> v1 >> v2;
v1 = LocateVNode(g, v1);
v2 = LocateVNode(g, v2);
ArcNode* p1 = new ArcNode;
p1->adjvex = v2 + 1;
p1->nextArc = g.vertices[v1].firstArc;
g.vertices[v1].firstArc = p1;
ArcNode* p2 = new ArcNode;
p2->adjvex = v1 + 1;
p2->nextArc = g.vertices[v2].firstArc;
g.vertices[v2].firstArc = p2;
}
return 1;
}
int CreateDG(ALGraph& g) {
cin >> g.vNum >> g.arcNum;
g.vertices = new VNode[g.vNum];
for (int i = 0; i < g.vNum; i++) {
cin >> g.vertices[i].data;
g.vertices[i].firstArc = NULL;
}
for (int i = 0; i < g.arcNum; i++) {
int v1, v2;
cin >> v1 >> v2;
v1 = LocateVNode(g, v1);
v2 = LocateVNode(g, v2);
ArcNode* p1 = new ArcNode;
p1->adjvex = v2 + 1;
p1->nextArc = g.vertices[v1].firstArc;
g.vertices[v1].firstArc = p1;
}
return 1;
}
void OutputDGraph(ALGraph g) {
for (int i = 0; i < g.vNum; i++) {
cout << g.vertices[i].data << ":";
ArcNode* p = g.vertices[i].firstArc;
while (p) {
cout << p->adjvex << " ";
p = p->nextArc;
}
cout << endl;
}
}
void WidthTraverseGraph(ALGraph g) {
queue<int> TraverseList;
int visited[1000];
memset(visited, 0, sizeof(visited));
cout << "v" << g.vertices->data << " ";
visited[0] = true;
TraverseList.push(g.vertices->data);
while (!TraverseList.empty()) {
int u = TraverseList.front();
TraverseList.pop();
ArcNode* p = g.vertices[LocateVNode(g,u)].firstArc;
while (p != NULL) {
if (!visited[LocateVNode(g, p->adjvex)]) {
cout << "v" << p->adjvex << " ";
visited[LocateVNode(g, p->adjvex)] = true;
TraverseList.push(p->adjvex);
}
p = p->nextArc;
}
}
}
int visited[1000];
void Depth_TG(ALGraph g, int v);
void DepthTraverseGraph(ALGraph g) {
memset(visited, 0, sizeof(visited));
for (int i = 0; i < g.vNum; i++) {
if (visited[i] == 0) {
Depth_TG(g, i);
}
}
}
void Depth_TG(ALGraph g,int v) {
cout << g.vertices[v].data << " ";
visited[v] = true;
ArcNode* p = g.vertices[v].firstArc;
while (p) {
int w = LocateVNode(g, p->adjvex);
if (!visited[w]) {
Depth_TG(g, w);
}
p = p->nextArc;
}
}
int main() {
ALGraph g;
CreateDG(g);
OutputDGraph(g);
DepthTraverseGraph(g);
return 0;
}
【7039】试编写算法,创建有向图邻接表,并深度优先遍历
最新推荐文章于 2021-12-29 09:43:06 发布