图的深度优先遍历算法
图的深度优先遍历算法,适用无向图和有向图
跟树的先序遍历实现思想相同,只不过多了个数组标记已访问的顶点
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
#define MAX_NUM 20
bool visited[5];
int global_counter = 10;
typedef struct {
int Vex[MAX_NUM];
int Edge[MAX_NUM][MAX_NUM];
int vexnum;
}Graph;
int FirstNeighbor(Graph g, int x){
for (int i = 1; i<=g.vexnum; i++) {
if (g.Edge[x][i]>0) {
return g.Vex[i];
}
}
return -1;
}
int NextNeighbor(Graph g, int x, int y){
for (int i = y+1; i<=g.vexnum; i++) {
if (g.Edge[x][i]>0) {
return g.Vex[i];
}
}
return -1;
}
void DFS(Graph g, int v);
void DFSTraverse(Graph g){
for (int i = 1; i<=g.vexnum; i++) {
visited[i] = false;
}
for (int i = 1; i<=g.vexnum; i++) {
if (!visited[i]) {
cout << "分量" << endl;
DFS(g, i);
}
}
}
void DFS(Graph g, int v){
cout << "elements:" << v << endl;
visited[v] = true;
int w = 0;
for (w = FirstNeighbor(g, v); w>=0; w = NextNeighbor(g, v, w)) {
if (!visited[w]) {
DFS(g, w);
}
}
}
int main(){
std::cout << "welcome, to my world!" << std::endl;
Graph graph;
for (int i=1; i<=5; i++) {
graph.Vex[i] = i;
}
for (int i=1; i<=5; i++) {
for (int j = 1; j<=5; j++) {
if (i==j) {
graph.Edge[i][j] = 0;
}else{
graph.Edge[i][j] = 0;
}
}
}
graph.Edge[1][2] = 1;
graph.Edge[1][3] = 1;
graph.Edge[2][4] = 1;
graph.Edge[2][5] = 1;
graph.Edge[4][3] = 1;
graph.vexnum = 5;
cout << "size of:" << sizeof(graph) <<endl;
DFSTraverse(graph);
return 0;
}
输出 welcome, to my world! size of:1684 分量 elements:1 elements:2 elements:4 elements:3 elements:5 Program ended with exit code: 0
|