如何利用R中的矩阵运算计算最短路径?

如何利用R中的矩阵运算计算最短路径?,r,adjacency-matrix,floyd-warshall,R,Adjacency Matrix,Floyd Warshall,我有一个表示图的邻接矩阵 M 1 2 3 4... 1 - 1 3 2 2 1 - 3 1 3 4 2 - 3 . . 我想执行Floyd算法来计算每对顶点之间的最短路径 我肯定能以O(N3)的复杂度对它们进行迭代 for ( i in 1 : n ) for ( j in 1 : n ) for ( k in 1 : n ) Floyd... 然而,当n=10^3时,R将无法经受迭代。所以我在寻找

我有一个表示图的邻接矩阵

M

   1  2  3  4...

   1  -  1  3  2
   2  1  -  3  1
   3  4  2  -  3
   .
   .
我想执行Floyd算法来计算每对顶点之间的最短路径

我肯定能以O(N3)的复杂度对它们进行迭代

for ( i in 1 : n )
  for ( j in 1 : n )
    for ( k in 1 : n )
      Floyd...
然而,当n=10^3时,R将无法经受迭代。所以我在寻找在矩阵运算中执行弗洛伊德算法的方法

附加参考 因此,我们可以参考

但是我仍然对如何在R中执行“repmat”感到困惑,它多次复制了mat

%%%%% Step 2: Compute shortest paths %%%%%
disp('Computing shortest paths...'); 

% We use Floyd's algorithm, which produces the best performance in Matlab. 
% Dijkstra's algorithm is significantly more efficient for sparse graphs, 
% but requires for-loops that are very slow to run in Matlab.  A significantly 
% faster implementation of Isomap that calls a MEX file for Dijkstra's 
% algorithm can be found in isomap2.m (and the accompanying files
% dijkstra.c and dijkstra.dll). 

tic; 
for k=1:N
     D = min(D,repmat(D(:,k),[1 N])+repmat(D(k,:),[N 1])); 
     if ((verbose == 1) & (rem(k,20) == 0)) 
          disp([' Iteration: ', num2str(k), '     Estimated time to completion: ', num2str((N-k)*toc/k/60), ' minutes']); 
     end
end

你让我留下答案。不过,我不完全确定你在找什么。您应该访问
所有最短路径的帮助页面
。使用这个函数看起来非常简单,它可以接受一个正方形矩阵并找到最靠岸的路径

e1071
中所有最短路径的代码如下

function (x) 
{
x <- as.matrix(x)
x[is.na(x)] <- .Machine$double.xmax
x[is.infinite(x) & x > 0] <- .Machine$double.xmax
if (ncol(x) != nrow(x)) 
    stop("x is not a square matrix")
n <- ncol(x)
z <- .C("e1071_floyd", as.integer(n), double(n^2), as.double(x), 
    integer(n^2), PACKAGE = "e1071")
z <- list(length = matrix(z[[2]], n), middlePoints = matrix(z[[4]] + 
    1, n))
z$length[z$length == .Machine$double.xmax] <- NA
z
}
<environment: namespace:e1071>
函数(x)
{

x我建议下载spa软件包的源代码,看看他们是如何做到的。您看过e1071软件包中的
allshortestpath
函数了吗?@Frank正是。它接受adj矩阵并计算所有最短路径。请留下答案。