I am trying to write an algorithm that takes an adjacency-matrix A and gives me the number of shortest paths between all pairs of nodes from length 1 to 20. For example, if there are 4 nodes that have a direct neighbor and 2 nodes that are connected by a shortest path of length two (and no paths longer than 2) the algorithm should return a vector [4 2 0 ... ].
My Idea is to use the fact that A^N gives to number of paths of length N between nodes.
Here is how my code looks so far:
function separations=FindShortestPaths(A)
#Save the original A to exponentiate
B = A;
#C(j,k) will be non-zero if there is a shorter path between nodes j and k
C = sparse(zeros(size(A)));
n = size(A,1);
#the vector in which i save the number of paths
separations = zeros(20,1);
for i = 1:20
#D(j,k) shows how many paths of length i there are from j to k
#if there is a shorter path it will be saved in C,
#so every index j,k that is non-zero in C will be zero in D.
D = A;
D(find(C)) = 0;
#Afterwards the diagonal of D is set to zero so that paths from nodes to themselves are not counted.
D(1:n+1:n*n) = 0;
#The number of remaining non-zero elements in D is the number of shortest paths of length i
separations(i) = size(find(D),1);
#C is updated by adding the matrix of length-i paths.
C = C + A;
#A is potentiated and now A(j,k) gives the number of length i+1 paths from j to k
A = A*B;
endfor
endfunction
I tried it with some smaller graphs of length 5 to 8 and it worked (each pair is counted twice though) but when I tried it with a larger graph it gave me odd numbers for some lengths, which can't be right as every pair is counted twice.
Edit:
Here is an example of one of the graphs I tried and with which it worked: Graph The adjacency Matrix of this graph is [010000 101010 010101 001000 010000 001000]
And the number of shortest paths of length n from any Node is:
n: 1 2 3 4 5 6
A: 1 2 2 0 0 0
B: 3 2 0 0 0 0
C: 3 2 0 0 0 0
D: 1 2 2 0 0 0
E: 1 2 2 0 0 0
F: 1 2 2 0 0 0
Total: 10 12 8 0 0 0
So the algorithm should (and in this case does) return a vector where the first 3 elements are 10 12 8 and the rest are zeros. However, with this bigger matrix it doesn't work.