Algorithms Part 1-Question 5- Dijkstra's shortest-path-最短路径算法

Algorithms: Design and Analysis, Part 1 

  最短路径算法题目要求

  本次要求对于一个200个点的无向图应用著名的Dijkstra算法求最短路径。可以选择用heap来计算,速度更快。我采用python语言,用了多个字典来加快速度。

In this programming problem you'll code up Dijkstra's shortest-path algorithm.
Download the text file here. (Right click and save link as).
The file contains an adjacency list representation of an undirected weighted graph with 200 vertices labeled 1 to 200. Each row consists of the node tuples that are adjacent to that particular vertex along with the length of that edge. For example, the 6th row has 6 as the first entry indicating that this row corresponds to the vertex labeled 6. The next entry of this row "141,8200" indicates that there is an edge between vertex 6 and vertex 141 that has length 8200. The rest of the pairs of this row indicate the other vertices adjacent to vertex 6 and the lengths of the corresponding edges.

Your task is to run Dijkstra's shortest-path algorithm on this graph, using 1 (the first vertex) as the source vertex, and to compute the shortest-path distances between 1 and every other vertex of the graph. If there is no path between a vertex v and vertex 1, we'll define the shortest-path distance between 1 and v to be 1000000.

You should report the shortest-path distances to the following ten vertices, in order: 7,37,59,82,99,115,133,165,188,197. You should encode the distances as a comma-separated string of integers. So if you find that all ten of these vertices except 115 are at distance 1000 away from vertex 1 and 115 is 2000 distance away, then your answer should be 1000,1000,1000,1000,1000,2000,1000,1000,1000,1000. Remember the order of reporting DOES MATTER, and the string should be in the same order in which the above ten vertices are given. Please type your answer in the space provided.

IMPLEMENTATION NOTES: This graph is small enough that the straightforward O(mn) time implementation of Dijkstra's algorithm should work fine. OPTIONAL: For those of you seeking an additional challenge, try implementing the heap-based version. Note this requires a heap that supports deletions, and you'll probably need to maintain some kind of mapping between vertices and their positions in the heap.

  算法实现

  这个算法比较简单,跟着课程走,实现要求的数据结构就ok了。当然最后要选择题目要求的点的距离,使用list comprehension可以加快这一过程。

  整个算法实现中,全部以字典实现,速度较快。

  代码如下:

f=open('dijkstraData.txt','r')
vertices=dict()
for line in f.readlines():
    tmp=line.split()
    try:
        vertices[int(tmp[0])]={int(x.split(',')[0]):int(x.split(',')[1]) for x in tmp[1:]}
    except:
        print('error'+tmp)
f.close

length=200
exped=[1]
noexped=list(range(2,length+1))
distance={x:0 for x in range(1,length+1)}

while len(exped)<length:
    maxlimit=1000000
    tmpdist=maxlimit
    lenvw=tmpdist
    for v in exped:
        for w in noexped:
            if w in vertices[v].keys():
                lenvw=distance[v]+vertices[v][w]
                if lenvw<tmpdist:
                    tmpdist=lenvw
                    tmpv=v
                    tmpw=w
    if tmpdist==maxlimit:break
    exped.append(tmpw)
    noexped.remove(tmpw)
    distance[tmpw]=tmpdist

print('distance is')
print(distance)
print('max distance is: '+str(max(distance.values())))
for ind in [7,37,59,82,99,115,133,165,188,197]:
    print(str(ind)+' is : '+str(distance[ind]))

  在对大型数据进行处理前,不妨采用小的数据集进行测试。

  这是测试使用的txt文件:

1 2,7 3,9 6,14
2 1,7 3,10 4,15
3 1,9 2,10 4,11 6,2
4 2,15 3,11 5,6
5 4,6 6,9
6 1,14 3,2 5,9

  计算结果是:

distance is
{1: 0, 2: 7, 3: 9, 4: 20, 5: 20, 6: 11}
max distance is: 20


你可能感兴趣的:(Algorithms Part 1-Question 5- Dijkstra's shortest-path-最短路径算法)