数据结构复习笔记(图)

本文介绍了图的两种存储结构——邻接矩阵和邻接表,并详细阐述了广度优先搜索(BFS)和深度优先搜索(DFS)算法,包括它们在单源最短路径问题中的应用。通过对图的遍历,可以进行有效的路径查找和访问所有顶点。
摘要由CSDN通过智能技术生成
//1.图的邻接矩阵存储结构
#define MaxVerterNum 100
typedef char VertexType;//顶点数据类型
typedef int EdgeType;//边权值数据类型
typedef struct{
	VertexType Vex[MaxVerterNum];//顶点表
	EdgeType Edge[MaxVerterNum][MaxVerterNum];
	int vexnum,arcnum;
}MGraph;

//2.图的邻接表存储结构
#define MaxVerterNum 100
typedef struct ArcNode{//边表结点
	int adjvex;//该弧指向的顶点的位置
	struct ArcNode *next;//指向下一条弧的指针
}ArcNode;
typedef struct VexNode{//顶点表结点
	VertexType data;//顶点信息
	ArcNode *first;//指向第一条依附该顶点的指针
}VexNode, AdjList[MaxVerterNum];
typedef struct{
	AdjList vertices;//邻接表
	int vexnum,arcnum;//图的顶点数和弧数
}ALGraph;

//3.广度优先搜索
bool visited[MAX_VERTEX_NUM];
void BFSTraverse(Graph G){
	for(int i=0;i<G.vexnum;i++)
		visited[i]=false;
	InitQueue(Q);
	for(int j=0;j<G.vexnum;j++)
		if(!visited[j])
			BFS(G,i);
}
void BFS(Graph G,int v){
	visit(v);
	visited[v]=true;
	EnQueue(Q,v);
	while(!IsEmpty(Q)){
		DeQueue(Q,v);
		for(w=FirstNeighbor(G,v);w>=0;w=NextNeighbor(G,v,w)){
			if(!visited[w]){
				visit(w);
				visited[w]=true;
				EnQueue(Q,w);
			}
		}
	}
}

//4.BFS求解单源最短路径问题
void BFS_MIN_Distance(Graph G,int u){
	for(int i=0;i<G.vexnum;i++)
		d[i]=999;
	visited[u]=true;
	d[u]=0;
	EnQueue(Q,u);
	while(!IsEmpty(Q)){
		DeQueue(Q,u);
		for(w=FirstNeighbor(G,u);w>=0;w=NextNeighbor(G,u,w)){
			if(!visited[w]){
				visited[w]=true;
				d[w]=d[u]+1;
				EnQueue(Q,w);
			}
		}
	}
}

//5.深度优先搜索DFS
bool visited[MAX_VERTEX_NUM];
void DFSTraverse(Graph G){
	for(int i=0;i<G.vexnum;i++)
		visited[i]=flase;
	for(int j=0;j<G.vexnum;j++)
		if(!visited[j])
			DFS(G,j);
}
void DFS(Graph G,int v){
	visted[v]=true;
	visit(v);
	for(w=FirstNeighbor(G,v);w>=0;w=NextNeighbor(G,v,w))
		if(!visited[w]){
			DFS(G,w);
		}
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值