-2

I have a network's data in tabular form (like in the screenshot) and would like to implement the Bellman-Ford algorithm on that. Every existing code for this is implemented to use an adjacency matrix. My file is in the form of an incidence list.

Imported into Julia, the network would be like the following:


start node i,end node j,c_ij
1,2,2
1,3,5
2,3,3
3,4,1
3,5,2
4,1,0
4,5,2
5,2,4

For example, I want to find all the distances from node source = [1,3].

My attempt (which is not working):

n = length(start_node)

for k in 1:source
    for i in 1:n
        for j in 1:n
        dist[i][j] = min(W[i][j], W[i][k] + W[k][j])
  
        end
    end
end

enter image description here

Zoe
  • 27,060
  • 21
  • 118
  • 148
  • Have you tried `bellman_ford_shortest_paths` from `LightGraphs.jl`? It doesn't exactly accept a list, but I imagine you can adapt your data? – AboAmmar May 13 '22 at 12:21
  • Hi @AboAmmar My actual data is vey long around 2K nodes in this format. Do you have any suggestion for adapting the data to the format of lightgraph.jl? –  May 13 '22 at 13:24
  • [Why should I not upload images of code/data/errors when asking a question?](https://meta.stackoverflow.com/q/285551/3404097) [Why are images of text, code and mathematical expressions discouraged?](https://meta.stackexchange.com/q/320052/266284) – philipxy May 16 '22 at 16:02
  • A [mre] includes cut & paste & runnable code, including smallest representative example input as code; desired & actual output (including verbatim error messages); tags & versions; clear specification & explanation. Give the least code you can give that is code that you show is OK extended by code that you show is not OK. (Debugging fundamental.) Find the first point in the execution where the state of the variables is not what you expect & say what you expect & why you expect it, justified by reference to authoritative documentation. (Debugging fundamental.) [ask] [Help] – philipxy May 16 '22 at 16:03

1 Answers1

2

Here is the code to parse your data:

using Graphs, DelimitedFiles, SparseArrays
dat="""1,2,2
1,3,5       
2,3,3       
3,4,1       
3,5,2       
4,1,0       
4,5,2       
5,2,4"""    
mx = readdlm(IOBuffer(dat),',',Int)
c = sparse(mx[:,1],mx[:,2],mx[:,3])
g = DiGraph(c)
bellman_ford_shortest_paths(g,1,c)
Przemyslaw Szufel
  • 40,002
  • 3
  • 32
  • 62