Ask Your Question
0

How to create a weighted graph and evaluate all the shortest path

asked 2022-12-05 16:00:07 +0200

Cyrille gravatar image

updated 2022-12-05 22:30:32 +0200

Sorry to ask this question but I cannot see how to start. I have a graph with say 3 vertex ${1, 2, 3, 4}$. The weights are :

1-2 : 6
1-3 : 2
1-4 : 2
2-3 : 1
2-4 : 5
3-4 : 3

I would like to know how to create such a simple graph in such a way to be able to evaluate the shortest path between any pair of two vertices. I have found how to do that for simple graphs not for weighted.

edit retag flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted
1

answered 2022-12-06 08:50:16 +0200

Using method shortest_path_all_pairs (check the documentation of the method)

sage: G = Graph([(1, 2, 6), (1, 3, 2), (1, 4, 2), (2, 3, 1), (2, 4, 5), (3, 4, 3)])
sage: G.shortest_path_all_pairs()
({1: {1: 0, 2: 1, 3: 1, 4: 1},
  2: {1: 1, 2: 0, 3: 1, 4: 1},
  3: {1: 1, 2: 1, 3: 0, 4: 1},
  4: {1: 1, 2: 1, 3: 1, 4: 0}},
 {1: {1: None, 2: 1, 3: 1, 4: 1},
  2: {1: 2, 2: None, 3: 2, 4: 2},
  3: {1: 3, 2: 3, 3: None, 4: 3},
  4: {1: 4, 2: 4, 3: 4, 4: None}})
sage: G.shortest_path_all_pairs(by_weight=True)
({1: {1: 0, 2: 3, 3: 2, 4: 2},
  2: {1: 3, 2: 0, 3: 1, 4: 4},
  3: {1: 2, 2: 1, 3: 0, 4: 3},
  4: {1: 2, 2: 4, 3: 3, 4: 0}},
 {1: {1: None, 2: 3, 3: 1, 4: 1},
  2: {1: 3, 2: None, 3: 2, 4: 3},
  3: {1: 3, 2: 3, 3: None, 4: 3},
  4: {1: 4, 2: 3, 3: 4, 4: None}})

The first dictionary is the shortest path distance. The second is a predecessor array. We can recover the paths from it.

edit flag offensive delete link more
0

answered 2022-12-06 04:34:24 +0200

licheng gravatar image

updated 2022-12-06 05:18:25 +0200

Try this:

import networkx as nx
G = nx.Graph()
e = [('1', '2', 6), ('1', '3', 2), ('1', '4', 2), ('2', '3', 1),('2','4',5),('3','4',3)]
G.add_weighted_edges_from(e)
print([p for p in nx.all_shortest_paths(G, source='1', target='2', weight='weight')])
# output: [['1', '3', '2']]
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2022-12-05 16:00:07 +0200

Seen: 242 times

Last updated: Dec 06 '22