Algorithms: Design and Analysis, Part 1, Programming Assignment #5
2016-09-06 13:55
661 查看
import heapq import sys fname = 'dijkstraData.txt' #fname = "tc.txt" fh = open(fname) lines = [line.rstrip('\n') for line in fh] # Generate graph as a list of dictionaries. # Index of list is the vertex, value is a disctionary where key is the outgoing vertex and value is the length of the edge. neighbor = [] d = dict() neighbor.append(d) for line in lines: part = line.split() v = int(part[0]) d = dict() for i in part[1:]: values = map(int, i.split(',')) d[values[0]] = values[1] neighbor.append(d) # Generating graph ends # Dijkstra s = 1 dest = [7,37,59,82,99,115,133,165,188,197] #dest = range(12) res = [] # vertices processded so far in a dictionary x = dict() # Computed shortest path distances in a dictionary/heap a = dict() x[s] = 0 a[s] = 0 while len(x) != len(neighbor): f = False for v in x.keys(): for w, e in neighbor[v].items(): if w in x: continue f = True cur = a[v] + e if w in a: a[w] = min(cur, a[w]) else: a[w] = cur #print "v:a[%d]:%d, e:%d, w:a[%d]:%d" % (v, a[v], e, w, a[w]) if f: min_e = sys.maxint min_v = 0 for w, e in a.items(): if (w not in x) and (e < min_e): min_e = e min_v = w x[min_v] = min_e #print "x[%d]:%d" % (min_v, x[min_v]) else: for w, e in a.items(): x[w] = e #print "exit" break #print "end of loop, a", a for d in dest: res.append(x.get(d, 0)) print res
相关文章推荐
- Stanford: Algorithms: Design and Analysis, Part 1 [Week 2]
- Algorithms: Design and Analysis, Part 1Problem Set #5
- Stanford - Algorithms: Design and Analysis, Part 1 - Week 2 Assignment: QuickSort
- Stanford - Algorithms: Design and Analysis, Part 2 - Week 2 Assignment: Clustering
- Stanford - Algorithms: Design and Analysis, Part 1 - Week 1 Assignment: number of inversions
- Stanford - Algorithms: Design and Analysis, Part 1 - Week 4 Assignment: strongly connected component
- Stanford - Algorithms: Design and Analysis, Part 1 - Week 5 Assignment: Dijkstra
- Stanford - Algorithms: Design and Analysis, Part 1 - Week 6 Assignment: hash table and heap
- Stanford - Algorithms: Design and Analysis, Part 1 - Week 3 Assignment: Contraction
- Stanford - Algorithms: Design and Analysis, Part 2 - Week 1 Assignment: Greedy and Prim
- Algorithms: Design and Analysis Note
- Design and Analysis of Distributed Algorithms
- Design and Analysis of Algorithms_Fundamentals of the Analysis of Algorithm Efficiency
- Stanford Algorithms: Design and Analysis, Part 2[week 6]
- Stanford Algorithms: Design and Analysis, Part 2 [Final Exam]
- Design and Analysis of Algorithms_Introduction
- Design and Analysis of Algorithms_Brute Froce
- [Coursera] Stanford Algorithms: Design and Analysis, Part 1,Final exam (2014)
- Stanford Algorithms: Design and Analysis, Part 1[week 2]
- Stanford Algorithms: Design and Analysis, Part 1[week 5]