优化这段代码,并写出来typedef struct ArcNode { int adjvex; struct ArcNode *nextarc; }ArcNode; typedef struct VNode { VertexType data; ArcNode *firstarc; }VNode, AdjList; typedef struct { AdjList vertices[MVNum]; int vexnum, arcnum; }ALGraph; void CreateUDG(ALGraph &G) { cout << "请输入顶点数和边数:\n"; cin>>G.vexnum>>G.arcnum; for(int i=0; i<G.vexnum; ++i) { cout << "请输入顶点信息:\n"; cin>> G.vertices[i].data; G.vertices[i].firstarc=NULL; } for(int k = 0; k<G.arcnum;++k) { int j; ArcNode *p1,*p2; cout<<"请输入每条边对应的两个顶点的序号:\n"; cin>>i>>j; p1=new ArcNode; p1->adjvex=j; p1->nextarc= G.vertices[i].firstarc; G.vertices[i].firstarc=p1; p2=new ArcNode; p2->adjvex=i; p2->nextarc= G.vertices[j].firstarc; G.vertices[j].firstarc=p2; } } void DFS(ALGraph G, int v) { //图G为邻接表类型 cout<<v; visited[v] = true; //访问第v个顶点 p= G.vertices[v].firstarc; //p指向v的边链表的第一个边结点 while(p!=NULL) //边结点非空 { w=p->adjvex; //表示w是v的邻接点 if(!visited[w]) DFS(G, w); //如果w未访问,则递归调用DFS p=p->nextarc; //p指向下一个边结点 } }
时间: 2024-02-07 18:04:15 浏览: 76
优化后的代码如下:
```c++
#include <iostream>
#include <cstring>
using namespace std;
const int MVNum = 100;
typedef int VertexType;
struct ArcNode {
int adjvex;
struct ArcNode* nextarc;
};
struct VNode {
VertexType data;
ArcNode* firstarc;
};
typedef VNode AdjList[MVNum];
struct ALGraph {
AdjList vertices;
int vexnum, arcnum;
};
void InputVertex(ALGraph& G) {
for (int i = 0; i < G.vexnum; ++i) {
cout << "请输入顶点信息:\n";
cin >> G.vertices[i].data;
G.vertices[i].firstarc = nullptr;
}
}
void InputEdge(ALGraph& G) {
for (int k = 0; k < G.arcnum; ++k) {
int i, j;
ArcNode* p1, * p2;
cout << "请输入每条边对应的两个顶点的序号:\n";
cin >> i >> j;
p1 = new ArcNode;
p1->adjvex = j;
p1->nextarc = G.vertices[i].firstarc;
G.vertices[i].firstarc = p1;
p2 = new ArcNode;
p2->adjvex = i;
p2->nextarc = G.vertices[j].firstarc;
G.vertices[j].firstarc = p2;
}
}
void CreateUDG(ALGraph& G) {
cout << "请输入顶点数和边数:\n";
cin >> G.vexnum >> G.arcnum;
InputVertex(G);
InputEdge(G);
}
bool visited[MVNum];
void DFS(ALGraph G, int v) {
cout << v;
visited[v] = true;
ArcNode* p = G.vertices[v].firstarc;
while (p != nullptr) {
int w = p->adjvex;
if (!visited[w]) {
DFS(G, w);
}
p = p->nextarc;
}
}
int main() {
memset(visited, false, sizeof(visited));
ALGraph G;
CreateUDG(G);
DFS(G, 0);
return 0;
}
```
阅读全文