花了点时间,写了下 无向图邻接表的代码 还有2中遍历,和教科书上差不多
#include<iostream>
#include<queue>
using namespace std;
# define MVNum 100
int visited[MVNum];
queue<int>q;
struct ArcNode
{
int adjvex;
ArcNode *nextarc;
};
typedef struct VNode
{
char data;
ArcNode *firstarc;
}Adjlist[MVNum];
struct ALGraph
{
Adjlist vertices;
int vexnum;
int arcnum;
};
ALGraph G;
int locatevex(ALGraph G,char x)
{
int i=0;
while(i<G.vexnum && x!=G.vertices[i].data)
i++;
if(i<G.vexnum)
return i;
}
void CreateUDG(ALGraph &G)
{
cout<<"请输入图的顶点数:\n";
cin>>G.vexnum;
cout<<"请输入图的弧数:\n";
cin>>G.arcnum;
char v1;
char v2;
int v1locate;
int v2locate;
ArcNode * p,* q;
cout<<"---------------输入图的信息---------------\n"<<endl;
cout<<"输入顶点信息(点对边)"<<endl;
for(int i=0;i<G.vexnum;i++)
{
cin>>G.vertices[i].data;
G.vertices[i].firstarc=NULL;
}
for(int k=1;k<=G.arcnum;k++)
{
cout<<"输入相关的边"<<endl;
cin>>v1>>v2;
v1locate=locatevex(G,v1);
v2locate=locatevex(G,v2);
p=new ArcNode;
p->adjvex=v2locate;
p->nextarc=G.vertices[v1locate].firstarc;
G.vertices[v1locate].firstarc=p;
q=new ArcNode;
q->adjvex=v1locate;
q->nextarc=G.vertices[v2locate].firstarc;
G.vertices[v2locate].firstarc=q;
}
}
void DFS(ALGraph G,int v)
{
visited[v]=1;
cout<<G.vertices[v].data<<" ";
for(ArcNode *p=G.vertices[v].firstarc;p;p=p->nextarc)
{
if(!visited[p->adjvex])
DFS(G,p->adjvex);
}
}
void dfstraverse(ALGraph G,int vex)
{
for(int i = 0;i < G.vexnum;i++)
visited[i]=0;
DFS(G,vex);
for(int v = 0;v < G.vexnum;v ++)
if(!visited[v])
DFS(G,v);
}
int BFS(ALGraph G)
{
for(int i = 0;i < G.vexnum;i++)
visited[i]=0;
q.empty();
int v;
int u;
for(v=0;v<G.vexnum;v++)
if(!visited[v])
{
visited[v]=1;
cout<<G.vertices[v].data<<" ";
q.push(v);
while(!q.empty())
{
u=q.front();
q.pop();
for(ArcNode *p=G.vertices[v].firstarc;p;p=p->nextarc)
if(!visited[p->adjvex])
{
visited[p->adjvex]=1;
cout<<G.vertices[p->adjvex].data<<" ";
q.push(p->adjvex);
}
}
}
return 1;
}
int isBegin()
{
int m=0;
cout<<"是否开始图的创建及遍历(0表示否)?\n";
cin>>m;
return m;
}
int main()
{
while(isBegin())
{
int a;
int t=0;
CreateUDG(G);
cout<<"输入图深度遍历的起点"<<endl;
cin>>a;
cout<<"深度优先遍历 :"<<endl;
DFS(G,a);
cout<<'\n';
cout<<"广度优先遍历 :"<<endl;
BFS(G);
cout<<'\n';
cout<<"是否清屏(0表示不) ?";
cin>>t;
if(t!=0)
{
system("cls");
}
}
return 0;
}