Directed graph demo
Draw a weighted directed graph with three nodes A, B and C such that the following properties hold:- The graph has only 3 edges.
- The shortest path from A to B is of length 3.
- The shortest path from A to C is of length 4.
- The shortest path from B to C is of length 1.
- The shortest path from B to A is of length 5.
- There are no paths from C to either A or B

]]>
1
0
0
directed_graph
0
1
10, 20, ...
3
0
18
#"
INF = float('inf')
error_count = 0
def error(s):
global error_count
print(s)
error_count += 1
try:
graph_rep = json.loads(student_answer)
node_id_to_name_map = {}
for i, node in enumerate(graph_rep['nodes']):
node_id_to_name_map[i] = node[0] if node[0] != '' else ('#' + str(i))
edges = graph_rep['edges']
graph = {}
for node_id, node_name in sorted(node_id_to_name_map.items()):
edges = []
for id0, id1, edge_label in graph_rep['edges']:
if id0 == node_id:
edges.append((node_id_to_name_map[id1], edge_label))
edges.sort()
graph[node_name] = edges
except json.JSONDecodeError as e:
raise Exception("Oops. Illegal graph received (exception {}). Please report (unless you did something silly yourself)".format(e))
# Now we add Floyd-Warshall
def allPairsShortestPath(g):
"""Return distance dictionary (a map from (u, v) to distance) computed
by Floyd-Warshall.
"""
dist = {}
for u in g:
for v in g:
dist[u, v] = INF
dist[u, u] = 0
for v, edge_label in g[u]:
try:
d = int(edge_label)
except ValueError:
d = 0
dist[u, v] = d
for mid in g:
for u in g:
for v in g:
newlen = dist[u, mid] + dist[mid, v]
if newlen < dist[u, v]:
dist[u, v] = newlen
return dist
distances = allPairsShortestPath(graph)
{% for TEST in TESTCASES %}
{{ TEST.testcode }}
{{ TEST.extra }}
{% if not loop.last %}
print(SEPARATOR)
{% endif %}
{% endfor %}]]>
1
1
0
0
0
1024
1
# Check the set of nodes
print(sorted(graph.keys()))
['A', 'B', 'C']
SHOW
SHOW
# Print connectivity (computed by
# hidden all-pairs shortest path code).
for src in 'ABC':
for dest in 'ABC':
if src != dest:
d = distances[src, dest]
print(src, dest, '-' if d == INF else d)
A B 3
A C 4
B A 5
B C 1
C A -
C B -
SHOW
# Check there are just 3 edges
print(sum([len(edgelist) for edgelist in graph.values()]))
3
SHOW