图的深搜与广搜

typedef char VType;
#define INF 65535
#define MAXVEX 100
//邻接矩阵 
typedef struct{
	VType vertices[MAXVEX];
	int edges[MAXVEX][MAXVEX];
	int vexnum,edgenum;
}MGraph; 
//邻接表
typedef struct ENode{
	int adjvex;
	struct ENode *next;
}ENode;
typedef struct VNode{
	VType data;
	ENode *firstedge;
}VNode,AdjList[MAXVEX];
typedef struct{
	AdjList vertices;
	int vexnum,edgenum;
}ALGraph;

//邻接矩阵深搜 
bool vis[MAXVEX];
void DFStraverse(MGraph G){
	for(int i=0;i<G.vexnum;i++){
		vis[i]=false;
	}
	for(int i=0;i<G.vexnum;i++){
		if(!vis[i]){
			DFS(G,i);
		}
	}
}
//口诀:打印访问循环搜索 
void DFS(MGraph G,int v){
	printf("%c",G.vertices[v]);
	vis[v]=true;
	for(int j=0;j<G.vexnum;j++){
		if(G.edges[v][j]==1&&!vis[j]){
			DFS(G,j);
		}
	}
}

//邻接矩阵广搜
bool vis[MAXVEX];
InitQueue(Q);
void BFSTraverse(MGraph G){
	for(int i=0;i<G.vexnum;i++){
		vis[i]=false;
	}
	for(int i=0;i<G.vexnum;i++){
		if(!vis[i]){
			BFS(G,i);
		}
	}
} 
//口诀:打印访问入队,出队打印访问入队
void BFS(MGraph G,int v){
	printf("%c",G.vertices[v]);
	vis[v]=true;
	EnQueue(Q,v);
	while(!IsEmpty(Q)){
		DeQueue(Q,v);
		for(int j=0;j<G.vexnum;j++){
			if(G.edges[v][j]==1&&!vis[j]){
				printf("%c",G.vertices[j]);
				vis[j]=true;
				EnQueue(Q,j);
			}
		}
	}
}

//邻接表广搜
void BFS(ALGraph G,int v){
	printf("%c",G.vertices[v].data);
	vis[v]=true;
	EnQueue(Q,v);
	while(!IsEmpty(Q)){
		DeQueue(Q,v);
		ENode* p=G.vertices[v].firstedge;
		while(p){
			if(!vis[p->adjvex]){
				printf("%c",G.vertices[p->adjvex].data);
				vis[p->adjvex]=true;
				EnQueue(Q,p->adjvex);
			}
			p=p->next; 
		}
	}
}

int d[MAXVEX];
void BFS_MIN_Distance(MGraph G,int u){
	for(int i=0;i<G.vexnum;i++)d[i]=INF;
	vis[u]=true;d[u]=0;
	EnQueue(Q,u);
	while(!IsEmpty(Q)){
		DeQueue(Q,u);
		for(int j=0;j<G.vexnum;j++){
			if(G.edges[u][j]==1&&!vis[j]){
				vis[j]=true;
				d[j]=d[u]+1;
				EnQueue(Q,j);
			}
		}
	}
} 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值