算法

图的DFS && BFS遍历

2017-04-04  本文已影响0人  codinRay

对图的深度优先遍历:

#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;
}
上一篇下一篇

猜你喜欢

热点阅读