-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathq4.py
More file actions
41 lines (36 loc) · 2.27 KB
/
q4.py
File metadata and controls
41 lines (36 loc) · 2.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#!/opt/local/bin/python
'''
In this assignment you will implement one or more algorithms for the all-pairs shortest-path problem. Here are data files describing three graphs: graph #1; graph #2; graph #3.
The first line indicates the number of vertices and edges, respectively. Each subsequent line describes an edge (the first two numbers are its tail and head, respectively) and its length (the third number). NOTE: some of the edge lengths are negative. NOTE: These graphs may or may not have negative-cost cycles.
Your task is to compute the "shortest shortest path". Precisely, you must first identify which, if any, of the three graphs have no negative cycles. For each such graph, you should compute all-pairs shortest paths and remember the smallest one (i.e., compute minu,v in Vd(u,v), where d(u,v) denotes the shortest-path distance from u to v).]
If each of the three graphs has a negative-cost cycle, then enter "NULL" in the box below. If exactly one graph has no negative-cost cycles, then enter the length of its shortest shortest path in the box below. If two or more of the graphs have no negative-cost cycles, then enter the smallest of the lengths of their shortest shortest paths in the box below.
OPTIONAL: You can use whatever algorithm you like to solve this question. If you have extra time, try comparing the performance of different all-pairs shortest-path algorithms!
'''
import numpy as np
import sys
maximum = 1000000
# Floyd-Warshall algorithm to solve All-Pairs Shortest Paths problem
def fw(graph,n,m):
# initialize the A matrix
a = np.ones((n,n),dtype=np.int)*maximum
for i in range(n):
a[i,i]=0
for i in range(m):
a[graph[i,0],graph[i,1]] = graph[i,2]
print "# start searching shortest path"
# start to search all shortest paths
for k in range(1,n):
for i in range(n):
a[i,:] = np.amin([a[i,:],a[i,k]+a[k,:]],axis=0)
# check negative cycles
if a[i,i]<0:
print "error in",i,k
exit()
# output
print "shortest path length:",a[:,:].min()
if __name__ == "__main__":
n,m = np.int_(np.fromfile(sys.argv[1],count=2,sep=' '))
graph = np.int_(np.loadtxt(sys.argv[1],skiprows=1))
graph[:,0] = graph[:,0]-1
graph[:,1] = graph[:,1]-1
fw(graph,n,m)