图的遍历
深度优先搜索
void dfs(int v)
{
visit[v] = 1;
cout << v << " ";
for (int j = 0; j < nv; ++j) {
if (MGraph[v][j] == 1&&visit[j]==0) {
dfs(j);
}
}
}
广度优先搜索
void bfs(int v)
{
queue<int> q;
q.push(v);
visit[v] = 1;
while (!q.empty()) {
int u = q.front();
q.pop();
cout << u << " ";
for (int j = 0; j < nv; ++j) {
if (MGraph[u][j] == 1 && visit[j] == 0) {
q.push(j);
visit[j] = 1;
}
}
}
}
Full Code
#include<iostream>
#include<queue>
using namespace std;
#define MAX_VERTEX 100
int MGraph[MAX_VERTEX][MAX_VERTEX];
int visit[MAX_VERTEX];
int nv, ne;
void creatMGraph();
void printMGraph();
void dfs(int v);
void bfs(int v);
int main()
{
creatMGraph();
cout << "请输入遍历起始结点:";
int v;
cin >> v;
bfs(v);
system("pause");
return 0;
}
void creatMGraph()
{
cout << "请输入结点数nv: ";
cin >> nv;
int i, j;
for (i = 0; i < nv; ++i) {
visit[i] = 0;
}
for (i = 0; i < nv; ++i) {
for (j = 0; j < nv; ++j) {
MGraph[i][j] = 0;
}
}
cout << "请输入边数ne:";
cin >> ne;
cout << "请依次输入边(例如:3 1): " << endl;
for (int k = 0; k < ne; ++k) {
cin >> i >> j;
MGraph[i][j] = 1;
MGraph[j][i] = 1;
}
}
void printMGraph()
{
int i, j;
for (i = 0; i < nv; ++i) {
for (j = 0; j < nv; ++j) {
cout << MGraph[i][j] << " ";
}
cout << endl;
}
}
void dfs(int v)
{
visit[v] = 1;
cout << v << " ";
for (int j = 0; j < nv; ++j) {
if (MGraph[v][j] == 1&&visit[j]==0) {
dfs(j);
}
}
}
void bfs(int v)
{
queue<int> q;
q.push(v);
while (!q.empty()) {
int u = q.front();
q.pop();
visit[u] = 1;
cout << u << " ";
for (int j = 0; j < nv; ++j) {
if (MGraph[u][j] == 1 && visit[j] == 0) {
q.push(j);
}
}
}
}