用C++實現,求有向圖中任意兩個結點間的所有路徑.其中圖的存儲結構爲鄰接矩陣.程序要帶注釋.

題目:

用C++實現,求有向圖中任意兩個結點間的所有路徑.其中圖的存儲結構爲鄰接矩陣.程序要帶注釋.

其中圖中的頂點爲1-35.鄰接矩陣是這樣的:

解答:

wait a minute 要所有路徑?還是最短路徑?
再問: 所有路徑,好的,非常感謝。
再答: 求所有路徑的意義是什麼??圖很大的話這路徑有很多條的啊
你要求的是任意兩點之間的最短距離吧?
再問: 因爲我這個圖中有1—35,共35個結點,我想求從結點1到其它各點的所有路徑。
再答: 這裡的所有路徑,都是最短路徑吧?鄰接矩陣讀取的是邊的權重還是單純的是否有邊?

能不能把linjiejuzhen.txt的大概內容描述一下?舉個簡單的例子也可以
再問: 不是的,比如從結點1到結點34,根據鄰接矩陣,是有很多路徑的。
再答: void PrintPath(int record[], int ed) {
\x09if (record[ed] != ed) {
\x09\x09PrintPath(record, record[ed]);
\x09\x09cout << " -> ";
\x09}
\x09cout << ed;
}

void PrintAllPathHelper(const MGraph& G, int st, int ed, int record[]) {
\x09if (ed == st) {
\x09\x09PrintPath(record, ed);
\x09}
\x09for (int i = 1; i < G.numVertexes; i++) {
\x09\x09if (G.arc[st][i] > 0 && record[i] == -1) {
\x09\x09\x09record[i] = st;
\x09\x09\x09PrintAllPathHelper(G, i, ed, record);
\x09\x09\x09record[i] = -1;
\x09\x09}
\x09}
}

void PrintAllPath(const MGraph& G, int st, int ed) {
\x09int record[MAXVEX];
\x09for (int i = 1; i < G.numVertexes; i++) {
\x09\x09record[i] = -1;
\x09}
\x09record[st] = st;
\x09PrintAllPathHelper(G, st, ed, record);
}
再問: 能不能改一下程序,使每兩條路徑之間有一個換行符,謝謝。
再答: void PrintPath(int record[], int ed) {
    if (record[ed] != ed) {
        PrintPath(record, record[ed]);
        cout << " -> ";
    }
    cout << ed;
}
 
void PrintAllPathHelper(const MGraph& G, int st, int ed, int record[]) {
    if (ed == st) {
        PrintPath(record, ed);
        cout << endl;
    }
    for (int i = 1; i < G.numVertexes; i++) {
        if (G.arc[st][i] > 0 && record[i] == -1) {
            record[i] = st;
            PrintAllPathHelper(G, i, ed, record);
            record[i] = -1;
        }
    }
}
 
void PrintAllPath(const MGraph& G, int st, int ed) {
    int record[MAXVEX];
    for (int i = 1; i < G.numVertexes; i++) {
        record[i] = -1;
    }
    record[st] = st;
    PrintAllPathHelper(G, st, ed, record);
}

添加新評論

暱稱
郵箱
網站