你想要的是一个“传递闭包算法”
Floyd-Warshall 算法就是其中一个很好的例子,尽管还有很多(很多)其他算法,例如Johnson 算法。在 Google Scholar 上进行快速搜索会为您指明其他一些来源和更多技术描述。
原始形式的 Floyd-Warshall 算法的代码(找到每个连接点之间的最短路径)是:
int dist[N][N]; // For some N
int i, j, k;
// Input data into dist, where dist[i][j] is the distance from i to j.
// If the nodes are unconnected, dist[i][j] should be infinity
for ( k = 0; k < N; k++ )
for ( i = 0; i < N; i++ )
for ( j = 0; j < N; j++ )
dist[i][j] = min( dist[i][j], dist[i][k] + dist[k][j] );
为您的使用场景修改此代码给出:
int dist[N][N]; // For some N
int i, j, k;
// Input data into dist, where dist[i][j] is the distance from i to j.
// If the nodes are unconnected, dist[i][j] should be infinity
for ( k = 0; k < N; k++ )
for ( i = 0; i < N; i++ )
for ( j = 0; j < N; j++ )
if(dist[i][k] && dist[k][j])
dist[i][j] = 1;
注意这里的下标顺序。具有此顺序的下标满足动态规划的标准,该标准确保路径逐渐改进并且始终是最优的。
时间复杂度为 O(N^3)。