僅透過 k 條邊就可以訪問的最短路徑
提供一個有向圖以及每對頂點的邊權,還提供兩個頂點 u 和 v。我們的任務是找出從頂點 u 到頂點 v 的最短距離,同時邊數恰好為 k。

要解決這個問題,我們將從頂點 u 開始,訪問所有相鄰頂點,然後使用 k - 1 作為 k 值,對相鄰頂點進行遞迴。
輸入和輸出
Input: The cost matrix of the graph. 0 10 3 2 ∞ 0 ∞ 7 ∞ ∞ 0 6 ∞ ∞ ∞ 0 Output: Weight of the shortest path is 9
演算法
shortKEdgePath(u, v, edge)
輸入 − 頂點 u 和 v,以及邊數。
輸出 − 最短路徑距離。
Begin if edge = 0 and u = v, then return 0 if edge = 1 and cost[u, v] ≠ ∞, then return cost[u, v] if edge <= 0, then return ∞ set shortPath := ∞ for all vertices i, do if cost[u, i] ≠ ∞ and u ≠ i and v ≠ i, then tempRes := shortKEdgePath(i, v, edge - 1) if tempRes ≠ ∞, then shortPath = minimum of shortPath and (cost[u,i]+tempRes done return shortPath End
示例
#include <iostream>
#define NODE 4
#define INF INT_MAX
using namespace std;
int cost[NODE][NODE] = {
{0, 10, 3, 2},
{INF, 0, INF, 7},
{INF, INF, 0, 6},
{INF, INF, INF, 0}
};
int minimum(int a, int b) {
return (a<b)?a:b;
}
int shortKEdgePath(int u, int v, int edge) {
if (edge == 0 && u == v) //when 0 edge, no path is present
return 0;
if (edge == 1 && cost[u][v] != INF) //when only one edge, and (u,v) is valid
return cost[u][v];
if (edge <= 0) //when edge is -ve, there are infinity solution
return INF;
int shortPath = INF;
for (int i = 0; i < NODE; i++) { //for all vertices i, adjacent to u
if (cost[u][i] != INF && u != i && v != i) {
int tempRes = shortKEdgePath(i, v, edge-1);
if (tempRes != INF)
shortPath = minimum(shortPath, cost[u][i] + tempRes);
}
}
return shortPath;
}
int main() {
int src = 0, dest = 3, k = 2;
cout << "Weight of the shortest path is " << shortKEdgePath(src, dest, k);
}輸出
Weight of the shortest path is 9
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP