图代码题汇总

图代码题汇总

图的结构体

  1. 邻接表存储
typedef struct ArcNode{
	int adjvex;
	struct ArcNode *nextarc;
}ArcNode, *Node;//边结点结构体

typedef struct{
	int data;
	ArcNode *firstarc;
}VNode;//顶点结构体

typedef struct{
	VNode adjlist[maxsize];
	int numver, numedg;
}AGraph;//图结构体
  1. 邻接矩阵存储
typedef struct{
	char vertex[maxsize];
	int edge[maxsize][maxsize];
	int numver, numedg;
}MGraph;

头插法建立图(邻接表结构体)

AGraph *func(AGraph *G, int v, int e){
	AGraph *G = new AGraph;
	G->numver = v;
	G->numedg = e;
	for(int i=0; i<v; i++){
		G->adjlist[i].firstarc = null;
	}
	for(int i=0; i<e; i++){
		int v1,v2;
		cin >> v1;
		cin >> v2;
		ArcNode *p = new ArcNode;
		p->adjvex = v1;
		p->nextarc = G->adjlist[v2].firstarc;
		G->adjlist[v2].firstarc = p;
		ArcNode *q = new ArcNode;
		q->adjvex = v2;
		q->nextarc = G->adjlist[v1].firstarc;
		G->adjlist[v1].firstarc = q;
	}
	return G;
}

2.图的广度优先遍历(BFS)

void BFS(AGraph *G, int v, int visit[]){
	for(int i=0; i<G->numvex; i++){
		visit[i] = 0;
	}
	int que[maxsize];//
	int front=0, rear=0;//
	cout << v << "";
	visit[v] = 1;
	que[++rear] = v;
	while(front != rear){
		int v = que[++front];
		ArcNode *p = G->adjlist[v].firstarc;
		while(p != null){
			if(visit[p->adjvex == 0])
				cout << p->adjvex << "";
				visit[p->adjvex] = 1;
				que[++rear] = p->adjvex;
			}
			p = p->nextarc;
		}
	}
}

3.利用BFS求无向图的最短路径

int func(AGraph *G, int v, int visit[], int &d[]){
	for(int i=0; i<G->numvex; i++){
		d[i] = INT16_MAX;
	}
	for(int i=0; i<G->numvex; i++){
		visit[i] = 0;
	}
	int que[maxsize];//
	int front=0, rear=0;//
	visit[v] = 1;
	d[v]=0;//
	que[++rear] = v;
	while(front != rear){
		int v = que[++front];
		ArcNode *p = G->adjlist[v].firstarc;
		while(p != null){
			if(visit[p->adjvex == 0])
				d[p->adjvex] = d[v] + 1;
				visit[p->adjvex] = 1;
				que[++rear] = p->adjvex;
			}
			p = p->nextarc;
		}
	}
}

你可能感兴趣的:(数据结构代码题,数据结构)