算法逻辑
1.广度优先算法
核心:从起始结点开始,先输出起始结点,再寻找与之相邻且未被访问的结点入队,当队不空时,输出队首元素,并寻找与之相邻且未被访问过的结点入队......
2.深度优先算法
代码
#include <iostream>
#include <queue>
using namespace std;
int* visit;
int num;
int** edge;
void DFS(int n) {
visit[n] = 1;
cout << n << " ";
for (int i = 0; i <num; i++) {//判断领顶点
if (edge[n][i] == 1 && visit[i] == 0)
DFS(i);
}
}
void BFS(int n) {
int temp = n;
queue<int>q;
q.push(temp);
while (!q.empty()) {
int t = q.front();
q.pop();
if (visit[t] == 0) {//没访问过就输出
cout << t << " ";
visit[t] = 1;
}
for (int i = 0; i <num; i++) {//把他的领顶点放到队中
if (edge[t][i] == 1 && visit[i] == 0) {
q.push(i);
}
}
}
}
void Reset() {
for (int i = 0; i < num; i++)
visit[i] = 0;
cout << endl;
}
int main() {
cin >> num;
//判断是否走过
visit = new int[num];
for (int i = 0; i < num; i++)
visit[i] = 0;
//领接矩阵
edge = new int* [num];
for (int i = 0; i < num; i++)
edge[i] = new int[num];
for (int i = 0; i < num; i++)
for (int j = 0; j < num; j++)
cin >> edge[i][j];
cout << "DFS" << endl;;
for (int i = 0; i < num; ++i) {
DFS(i);
Reset();
}
cout << "WFS" << endl;;
for (int i = 0; i < num; ++i) {
BFS(i);
Reset();
}
}