BFS最短路径

#include <iostream>
#include <queue>
#include <cstring> // for memset
#define Max 503
#define INF 0xcffff

using namespace std;

typedef struct AMGraph {
    int vex, arc;
    int arcs[Max][Max];
} AMGraph;

queue<int> a;
bool visited[Max];
int dist[Max];
int path[Max];

int firstnode(AMGraph& G, int x) {
    for (int i = 1; i <= G.vex; i++) {
        if (G.arcs[x][i] > 0 && !visited[i])
            return i;
    }
    return -1;
}

int nextnode(AMGraph& G, int x, int next) {
    for (int i = next + 1; i <= G.vex; i++) {
        if (G.arcs[x][i] > 0 && !visited[i])
            return i;
    }
    return -1;
}

void BFS(AMGraph& G, int x) {
    for (int i = 1; i <= G.vex; i++) {
        path[i] = -1;
        dist[i] = INF;
        visited[i] = false;
    }
    dist[x] = 0;
    visited[x] = true;
    a.push(x);
    while (!a.empty()) {
        int current = a.front();
        cout << current << " ";
        a.pop();
        for (int w = firstnode(G, current); w > 0; w = nextnode(G, current, w)) {
            if (!visited[w]) {
                a.push(w);
                visited[w] = true;
                path[w] = current;
                dist[w] = dist[current] + 1;
            }
        }
    }
    cout << endl;
}

void find(int x) {
    if (path[x] == -1) {
        cout << x;
    }
    else {
        find(path[x]);
        cout << "->" << x;
    }
}

void putin(AMGraph& G) {
    int u, v;
    cin >> G.vex >> G.arc;

    for (int i = 1; i <= G.vex; i++) {
        for (int j = 1; j <= G.vex; j++) {
            if (i == j) G.arcs[i][j] = 0;
            else G.arcs[i][j] = -1; // 初始化为-1,表示无边
        }
    }

    for (int i = 0; i < G.arc; i++) {
        cin >> u >> v;
        G.arcs[u][v] = 1;
        G.arcs[v][u] = 1;
    }
}

void putout(AMGraph& G, int x) {
    cout << "dist[]: ";
    for (int i = 1; i <= G.vex; i++) {
        cout << dist[i] << " ";
    }
    cout << endl;
    for (int i = 1; i <= G.vex; i++) {
        cout << "V" << x << "到V" << i << "的最短路徑是:" ;
        find(i);
        cout << endl;
    }
}

int main() {
    AMGraph G;
    putin(G);
    int point = 2;
    BFS(G, point);
    putout(G, point);
    return 0;
}

/*
5 7
1 3
1 5
2 5
2 4
4 5
3 2
3 5
*/

需要的辅助数组太多了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值