C language adjacency list of breadth-first search

1. There are two types for graph traversal traversal methods: depth-first traversal and breadth-first traversal, traversing the tree for the difference is the need to increase an array of tags to mark nodes visited, if we visited the no longer able to access the

2. The following is a C language implementation breadth-first traversal:

① first need to store a map, use the adjacent table below is the way to store map (using the adjacent table to store the map in my previous blog write: https://blog.csdn.net/qq_39445165/article/details / 92692027 )

② For breadth-first search queue we need the help to achieve the specific algorithm implementation process is as follows:

1) Take any one vertex accessed FIG enqueuing and vertex marked as visited

2) When the queue is not empty when the loop is executed: dequeued, checking all dequeued vertex adjacent vertices, access has not been visited adjacent vertices and enqueue

3) When the queue is empty when the end of the cycle, breadth-first search ends

3. The following is the code table for the adjacent storage structure implemented:

#include<stdio.h>
#include<iostream>
#define maxSize 10000
#include<malloc.h>
using namespace std;
typedef struct ArcNode{
	int adjvex;
	struct ArcNode *nextarc;
	int info;
}ArcNode; 

typedef struct{
	int data;
	ArcNode *firstarc;
}Vnode; 

typedef struct{
	Vnode adjlist[maxSize];
	int n, e;
}AGraph;

AGraph *graph;
//需要先进行初始化为0 
int visit[maxSize] = {0};
void  insertNode(ArcNode *node, ArcNode *newNode){
	ArcNode *p = node;
	while(p->nextarc != NULL){
		p = p->nextarc;
	}
	p->nextarc = newNode;	
}

void create(){
	graph = (AGraph*)malloc(sizeof(AGraph));
	cout << "输入顶点的数目: " << endl;
	cin >> graph->n;
	cout << "输入图中边的数目: " << endl;
	cin >> graph->e;
	int u = -1, v = -1, weight = -1;
	for(int i = 0; i < graph->n; i++){
		graph->adjlist[i].firstarc = NULL;
	}
	
	ArcNode *node; 
	for(int i = 0; i < graph->e; i++){
		cin >> u >> v >> weight;
		node = (ArcNode *)malloc(sizeof(ArcNode));
		node->adjvex = v; 
		node->info = weight;
		node->nextarc = NULL;
		graph->adjlist[u].data = u;
		if(graph->adjlist[u].firstarc == NULL){
			graph->adjlist[u].firstarc = node; 
		}else{
			insertNode(graph->adjlist[u].firstarc, node); 
		}	
	} 
}

void bfs(AGraph *G, int v){
	//使用到循环队列来进行处理 
	ArcNode *p;
	int que[maxSize], front = 0, rear = 0;
	int j;
	cout << v << " ";
	visit[v] = 1;
	rear = (rear + 1) % maxSize;
	que[rear] = v;
	while(front != rear){
		front = (front + 1) % maxSize;
		j = que[front];
		p = G->adjlist[j].firstarc;
		while(p != NULL){
			if(visit[p->adjvex] == 0){
				cout << p->adjvex << " ";
				visit[p->adjvex] = 1;
				rear = (rear + 1) % maxSize;
				que[rear] = p->adjvex;
			}
			p = p->nextarc;	
		}
	}	
}

int main(void){
	create();
	bfs(graph, 0);
	return 0;
} 

 

 

Guess you like

Origin blog.csdn.net/qq_39445165/article/details/92722764