图邻接表存储+DFS

#include<iostream>
using namespace std;
typedef int vertype ;
#define max 100
int book[max];
struct ArcNode
{
	int adjvex;//记录一条边的右顶点的下标
	int weight;
	ArcNode *next;//下一条边
};
struct VNode
{
	 vertype data;//顶点的类型
	 ArcNode *firstarc;//顶点的第一条边,是连接顶点数组与单链表的桥梁
};
struct Graph 
{
	int vernum;//图顶点的总个数
	int arcnum;//图边的总个数
	VNode ver[max];//顶点数组
};
int change(Graph *G,vertype v)
{
	for(int i=1;i<=G->vernum;i++)
	{
		if(G->ver[i].data==v)
			return i;
	}
}
void creat(Graph *G)
{
	cout<<"输入图的顶点数和边数"<<endl;
	cin>>G->vernum>>G->arcnum ;
	cout<<"输入"<<G->vernum<<"个顶点的信息"<<endl;
	for(int i=1;i<=G->vernum;i++)
	{
		cin>>G->ver[i].data;
		G->ver[i].firstarc=NULL;//初始化顶点数组和边
		book[i]=0;
	}
	cout<<"输入"<<G->arcnum<<"个边的信息(v1,v2,weight)"<<endl;
	for(int i=1;i<=G->arcnum;i++)
	{
		int v1,v2,weight;
		int t1,t2;
		cin>>t1>>t2>>weight;
		v1=change(G,t1);
		v2=change(G,t2);
		ArcNode *node=new ArcNode;
		node->adjvex=v2;//一条边的右端点
		node->next=NULL;//新创建的结点初始化
		node->weight=weight;

		/*ArcNode *tnode=new ArcNode;
		tnode->adjvex=v1;
		tnode->next =NULL;
		tnode->weight=weight;                //这段代码加上就是无向图了
        tnode->next=G->ver[v2].firstarc;
		G->ver[v2].firstarc=tnode;
		*/

		node->next=G->ver[v1].firstarc;         //这里是头插法
		G->ver[v1].firstarc=node; 

		/*
		ArcNode *p=G->ver[v1].firstarc;//特别注意这里是v1的第一条边,v2是插入v1的第一条边或者 
                                            是v1的next条边
		if(p==NULL)
			G->ver[v1].firstarc=node;//这里也是v1
		else
		{
			while(p->next)                               / /尾插法
			{
				p=p->next;
			}
			p->next=node;
		}
		*/
	}
}
//深度优先
//标记源点
//输出源点
//寻找到源点的第一条边
//如果存在且没有被标记
//那么就标记,输出,然后再寻找源点第一条边的第一条边(即递归,再次调用该函数)
//当源点的第一条边的第一条边的第一条边....为空的时候,就会回溯到倒数第二条边这个时候就会找倒数第二条边的第一条边的next
void DFS(Graph *G,int v)
{
	book[v]=1;
	cout<<G->ver[v].data<<" ";
	ArcNode *p=G->ver[v].firstarc;//这个函数是对于连通图来说遍历的,非连通图需要加入下面函数
	while(p)
	{
		if(book[p->adjvex]==0)
		DFS(G,p->adjvex);
		p=p->next;
	}
}
void DFSTravese(Graph *G)
{
	for(int i=1;i<=G->vernum;i++)
     {	  book[i]=0;   	 }
	for(int i=1;i<=G->vernum;i++)//适用于非连通图的
	{
		if(book[i]==0)
		  DFS(G,i);
	}
}

void print(Graph *G)
{
	for(int i=1;i<=G->vernum;i++)
	{
		cout<<"顶点"<<G->ver[i].data<<"的边有:";
		cout<<endl;
		ArcNode *p=G->ver[i].firstarc;
		if(p==NULL)
			cout<<"无边"<<endl;
			while(p!=NULL)
		  {
			cout<<"邻边:"<<G->ver[p->adjvex].data<<"权重:"<<p->weight;
			cout<<endl;
			p=p->next;
		  }
		cout<<endl;
		}
}
int main()
{
	Graph *G=new Graph;
	creat(G);
	print(G);
	DFSTravese(G);
	system("pause");
}

猜你喜欢

转载自blog.csdn.net/m0_53389337/article/details/121410861