图的创建和DFS,BFS算法C++(详细)

结构体
typedef struct ArcNode
{
int adjvex; //该边指向的结点位置
struct ArcNode *nextarc; /指向下一条边/
int info; //可以表示权值
}ArcNode;

typedef struct
{
char data; /顶点域/
ArcNode *firstarc; /表头指针/
}VNode;

typedef struct AGraph
{
VNode adjlist[maxSize]; /邻接表/
int n,e; /顶点数和边数/
}AGraph;

创建图

AGraph* Create_Graph( )
{

	AGraph *G;
	G=(AGraph *)malloc(sizeof(AGraph));   //分配内存很重要,不然错在哪都不知道 
	int i;
	printf("请输入顶点数和边数(输入格式为:顶点数,边数)\n");
//	cin>>G->n>>G->e;
	scanf("%d %d",&(G->n),&(G->e)); /*读入顶点数和边数*/
	printf("请输入顶点信息:\n");
	for (i=0;i<G->n;i++) /*建立有n 个顶点的顶点表*/
		{
//			scanf("\n%c",&(G->adjlist[i].data)); /*读入顶点信息*/
            cin>>G->adjlist[i].data;
			G->adjlist[i].firstarc=NULL; /*顶点的边头指针设为空*/
		}
	printf("请输入边的信息(输入格式为:i,j):\n");
//	printf("请输入边的信息(输入格式为:i,j,info):\n");
	int j,k;
	ArcNode *s;
	for (k=0;k<G->e;k++)     /*建立边表*/
	{
        cin>>i>>j;
	//	scanf("%d,%d\n",&i,&j,&m);   /*读入边的顶点对应序号*/
		s=(ArcNode*)malloc(sizeof(ArcNode)); /*生成新边表结点s*/
		s->adjvex=j;   /*该边指向的结点数组下标*/
		s->nextarc=G->adjlist[i].firstarc; /*头插法插入结点*/
	//	s->info=m;
		G->adjlist[i].firstarc=s;

		/*无向图再加上这个
		s=(ArcNode*)malloc(sizeof(ArcNode));
		s->adjvex=i;   //该边指向的结点数组下标
		s->nextarc=G->adjlist[i].firstarc; //头插法插入结点
//		s->info=m;
		G->adjlist[i].firstarc=s;*/
	}
	cout << "邻接表如下:" << endl;
	for (int i = 0; i < G->n; i++) {
		ArcNode *p = G->adjlist[i].firstarc;
		while (p!=NULL)
		{	
			cout <<"<"<< G->adjlist[i].data <<","<<G->adjlist[p->adjvex].data<<">";
			p = p->nextarc;
		}
		cout<<endl; 
	}
	return G;
}

DFS

int visit[maxSize]={0};
void DFS(AGraph *G,int v)
{
	ArcNode *p;
	visit[v]=1;
	printf("%c\n",G->adjlist[v].data);
	p=G->adjlist[v].firstarc;
	while(p!=NULL)
	{
		if(visit[p->adjvex]==0)
			DFS(G,p->adjvex);
		p=p->nextarc;
	}
 }

BFS

void BFS(AGraph *G,int v,int visit[maxSize]) 
{
	ArcNode *p;
	int que[maxSize],front=0,rear=0;
	int j;
	printf("%c\n",G->adjlist[v].data);
	visit[v]=1;
	rear=(rear+1)%maxSize;
	que[rear]=v; 
	while(rear!=front)
	{
		front=(front+1)%maxSize;
		j=que[front];
		p=G->adjlist[j].firstarc;
		while(p!=NULL)
		{
			if(visit[p->adjvex]==0)
			{
			printf("%c\n",G->adjlist[p->adjvex].data);
			visit[p->adjvex]=1;
			rear=(rear+1)%maxSize;
			que[rear]=p->adjvex;	
			 }
			 p=p->nextarc; 
		 } 		
		
	}
}

示例

int main()
{
	AGraph *G;
	G=Create_Graph();
//	DFS(G,0);
	BFS(G,0,visit); 
}
/*
请输入顶点信息:

请输入边的信息(输入格式为:i j):
5 7
0
1
2
3
4
0 1
0 3
0 4
1 2
1 4
2 0
3 2

*/

你可能感兴趣的:(笔记,图论,bfs,dfs)