C ++ breadth adjacency matrix storage map search priority

1. In the data structure for the main memory of FIG three ways, respectively, the adjacency matrix, and adjacent table edge set, the first two commonly used, is used in the following C ++ language and FIG adjacency matrix store traversal achieved BFS

2. The following is a specific implementation process:

FIG adjacency matrix storage ① achieve mainly two-dimensional array used to store, if it is not we need to mark the start and end vertex apex ends from the start vertex to the end vertex values ​​corresponding to the FIG., A regular approach is flag of 1 indicates that the graph [u] [v] = 1 and the graph [v] [u] = 1 if it is the case then the right of FIG array can be stored inside the edge weight

② used herein have the two-dimensional array to store the right figure, when the input data we can store the position corresponding to the start and end of weights corresponding to relatively easily as compared to the adjacency matrix for the adjacency matrix for the operation

So we need to map the breadth breadth ③ good memory map after first search, breadth-first search for that we need the help of the queue to traverse operation pattern, pop up a node, adding a number of neighbors then it may implement a priority traverse, since there may FIG loop, so in this case also need to set a flag array to compare whether the current vertex been visited

Specific FIG follows:

Test data are as follows:

6
8
0 1 1
0 2 2
0 3 4
1 2 5
2 3 9
2 4 9
2 5 6
4 5 2

3. The following is a specific code:

#include<stdio.h>
#include<iostream>
#include<queue>
#define maxSize 1000
#define INF 100000000
using namespace std;
bool inq[maxSize] = {false}; 
int n, edges, G[maxSize][maxSize];
void bfs(int u){
	queue<int> q;
	q.push(u);
	inq[u] = true;
	while(!q.empty()){
		int u = q.front();
		cout << u << " ";
		q.pop();
		for(int v = 0; v < n; v++){
			if(inq[v] == false && G[u][v] != INF){
				q.push(v);
				inq[v] = true;	
			}
		}
	}
}

int main(void){
	cout << "输入图中的顶点数: ";
	cin >> n;
	//先初始化G数组为INF 
	for(int i = 0; i < n; i++){
		for(int j = 0; j < n; j++){
			G[i][j] = INF;
		}
	}		
	cout << endl;
	cout << "输入图中的边数: ";
	cin >> edges;
	cout << endl << "输入图中的起始顶点, 结束顶点和边的权重: " << endl;
	int u = -1, v = -1, weight = -1;
	for(int i = 0; i < edges; i++){
		cin >> u >> v >> weight;
		G[u][v] = weight;
	}
	bfs(0); 
	return 0;
} 

 

Guess you like

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