欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

图的DFS && BFS遍历

程序员文章站 2022-05-21 23:17:43
...

对图的深度优先遍历:

#include <iostream>
#define MAXE 1000
#define MAXN 100
#define INF 0x3f3f3f3f
using namespace std;
int g[MAXE][MAXN];
bool vis[MAXN] = { 0,1 };
int n, e, cnt;
void DFS(int cur) {
    cout << cur << " ";
    cnt++;
    if (cnt == n)
        return;
    for (int i = 1; i <= n; ++i) {
        if (g[cur][i] == 1 && !vis[i]) {
            vis[i] = true;
            DFS(i);
        }
    }
}
int main() {
    cin >> n >> e; // 顶点数, 边数
    for (int i = 1; i <= n; ++i)
        for (int j = 1; j <= n; ++j)
            g[i][j] = (i == j ? 0 : INF);
    for (int i = 1; i <= e; ++i) {
        int f, t;
        cin >> f >> t;
        g[t][f] = 1;
        g[f][t] = 1;
    }
    DFS(1);
    return 0;
}

对图的广度优先遍历:

#include <iostream>
#include <queue>
#define MAXN 100
#define MAXE 1000
#define INF 0x3f3f3f3f
using namespace std;
int g[MAXE][MAXN];
int n, e;
int main() {
    cin >> n >> e; // 顶点数, 边数
    for (int i = 1; i <= n; ++i)
        for (int j = 1; j <= n; ++j)
            g[i][j] = (i == j ? 0 : INF);
    for (int i = 1; i <= e; ++i) {
        int f, t;
        cin >> f >> t;
        g[f][t] = 1;
        g[t][f] = 1;
    }
    queue<int> q;
    bool vis[MAXN] = { 0,1 };
    q.push(1);
    while (!q.empty()) {
        int cur = q.front();
        for (int i = 1; i <= n; ++i) {
            if (!vis[i] && g[cur][i] == 1) {
                q.push(i);
                vis[i] = true;
            }
        }
        cout << cur << ' ';
        q.pop();
    }
    return 0;
}