这是我准备考研的时候整理的代码。
一、邻接表的定义
typedef struct ArcNode{
int data;
struct ArcNode *nextArc;
}ArcNode;
typedef struct VNode{
int data;
ArcNode *firstArc;
}VNode,Adjlist;
typedef struct ALGraph{
Adjlist vertices[MAXSIZE];
int vexnum,arcnum;
}ALGraph;
二、创建图
void CreateALGraph(ALGraph &g){
cout<<"Now create ALGraph: vexnum arcnum"<<endl;
cin>>g.vexnum>>g.arcnum;
for(int i=1;i<=g.arcnum;i++){
g.vertices[i].firstArc=NULL;
g.vertices[i].data=i;
}
//输入边
cout<<"Now input the arcs:"<<endl;
for(int i=0;i<g.arcnum;i++){
//cout<<"input arc"<<i+1<<":";
int u,v;
cin>>u>>v;
if (g.vertices[u].firstArc==NULL){
//cout<<"new firstArc"<<endl;
ArcNode *q=(ArcNode*)malloc(sizeof(ArcNode));
q->data=v;
q->nextArc=NULL;
g.vertices[u].firstArc=q;
}
else{
ArcNode *p=g.vertices[u].firstArc;
while (p->nextArc!=NULL){
p=p->nextArc;
}
ArcNode *q=(ArcNode*)malloc(sizeof(ArcNode));
q->data=v;
q->nextArc=NULL;
p->nextArc=q;
}
}
//输出邻接表
cout<<endl<<"Now output arcs info:"<<endl;
for (int i = 1; i <= g.vexnum; i++){
cout<<"vertex "<<g.vertices[i].data<<" :";
ArcNode *p=g.vertices[i].firstArc;
while (p!=NULL){
cout<<p->data<<" ";
p=p->nextArc;
}
cout<<endl<<endl;
}
}
三、DFS遍历
1、递归实现
int visited[MAXSIZE];
/*
清空visited[]
*/
void clearVisited(){
for(int i=0;i<MAXSIZE;i++){
visited[i]=0;
}
}
/*
DFS遍历(递归实现)
*/
void DFS(ALGraph g,int u){
visited[u]=1;
cout<<u<<" ";
ArcNode *p;
p=g.vertices[u].firstArc;
while(p!=NULL){
if(!visited[p->data]){
visited[p->data]=1;
DFS(g,p->data);
}
p=p->nextArc;
}
}
void DFSTraverse(ALGraph g){
cout<<"Now start DFS: "<<g.arcnum<<" arcs and "<<g.vexnum<<" vertixs"<<endl;
for(int i=1;i<=g.arcnum;i++){
visited[i]=0;
}
for(int i=1;i<=g.arcnum;i++){
if(visited[i]==0){
cout<<"DFS from new connected component: "<<endl;
DFS(g,i);
}
cout<<endl;
}
}
2.非递归实现
void DFS_non_recursion(ALGraph g,int u){ //DFS非递归
cout<<endl<<"Now start DFS_non_recursion"<<endl;
clearVisited();
int stack[MAXSIZE];
int top=-1;
stack[++top]=u;
visited[u]=1;
cout<<u<<" ";
while (top!=-1)
{
int w=stack[top];
/*
cout<<endl<<'['; //显示栈内容
for(int i=0;i<=top;i++){
cout<<stack[i]<<" ";
}
cout<<']'<<endl;
*/
ArcNode *p=g.vertices[w].firstArc;
bool flag=true; //用来判断是否出栈
while (p!=NULL)
{
if(visited[p->data]==0){
flag=false;
visited[p->data]=1;
cout<<p->data<<" ";
stack[++top]=p->data; //入栈
break;
}
p=p->nextArc;
}
if(flag){
top--; //出栈
}
}
}
四、BFS遍历
void BFS(ALGraph g,int u){
cout<<endl<<"Now start BFS"<<endl;
visited[u]=1;
queue<int> q;
q.push(u);
ArcNode *p;
while (!q.empty()){
int w=q.front();
q.pop();
p=g.vertices[w].firstArc; //出栈
cout<<w<<" ";
while (p!=NULL){
if(visited[p->data]==0){
visited[p->data]=1;
q.push(p->data);
}
p=p->nextArc;
}
}
}
void BFSTraverse(ALGraph g){
cout<<endl<<"Now start BFS"<<endl;
clearVisited();
for(int i=1;i<g.vexnum;i++){
if(visited[g.vexnum]==0){
cout<<"BFS from new connected component: "<<endl;
BFS(g,i);
}
}
}