C ++ depth first search graph adjacency matrix storage

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 storage implement depth-first search traversal

2. The following is a specific implementation process:

① For depth-first traversal adjacency matrix storage map is relatively simple, only need to use an array of tags to mark whether the current vertex has been accessed to find a neighbor from a start vertex graph, which is the current vertex and the presence of other Contact vertices, each vertex then visited a marked vertex has been visited

After ② find the current neighbors and from then current starting point adjacent continue to search for a relationship with the neighbors of the current point, the final figure dfs search ends so all vertices have been visited

FIG example as follows:

Test data are as follows:

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

3. The following is a specific code:

#include<stdio.h>
#include<iostream>
#include<queue>
#include<algorithm>
#define maxSize 100
#define INF 100000
using namespace std;
bool vis[maxSize] = {false}; 
int n, edges, G[maxSize][maxSize];
void dfs(int u){
	vis[u] = true;
	cout << u << " ";
	for(int v = 0; v < n; v++){
		if(vis[v] == false && G[u][v] != INF){
			dfs(v);	
		}
	}
}

int main(void){
	cout << "输入图中的顶点数: ";
	cin >> n;
	fill (G[0], G[0] + maxSize * maxSize, 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;
	}
	for(int i = 0; i < n; i++){
		if(vis[i] == false){
			dfs(0);
		}
	}
	return 0;
} 

 

Guess you like

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