图
#include <iostream>
#include <queue>
using namespace std;
#define MAX_VERTEX_NUM 20
bool visited[MAX_VERTEX_NUM];
typedef struct {
int vertex[MAX_VERTEX_NUM];
int edge[MAX_VERTEX_NUM][MAX_VERTEX_NUM];
int vexNum, edgeNum;
} Graph;
void visit(int v) {
cout << v << " ";
}
//BFS
void BFS(Graph G, int v){
queue<int> Q;
visit(v);
visited[v] = true;
Q.push(v);
while( !Q.empty() ){
int u = Q.front();
Q.pop();
for(int w = 0; w < G.vexNum; w++){
if(G.edge[u][w] && !visited[w]){
visit(w);
visited[w] = true;
Q.push(w);
}
}
}
}
void BFSTraverse(Graph G){
for(int i = 0; i < G.vexNum; i++)
visited[i] = false;
for(int i = 0; i < G.vexNum; i++)
if( !visited[i] )
BFS(G, i);
}
//DFS
void DFS(Graph G, int v) {
visit(v);
visited[v] = true;
for (int w = 0; w < G.vexNum; w++) {
if (G.edge[v][w] && !visited[w]) {
DFS(G, w);
}
}
}
void DFSTraverse(Graph G) {
for (int i = 0; i < G.vexNum; i++) {
visited[i] = false;
}
for (int i = 0; i < G.vexNum; i++) {
if (!visited[i]) {
DFS(G, i);
}
}
}
评论区