您的位置:首页 > 其它

Project Euler:Problem 83 Path sum: four ways

2015-07-21 21:51 274 查看
In the 5 by 5 matrix below, the minimal path sum from the top left to the bottom right, by moving left, right, up, and down, is indicated in bold red and is equal to 2297.

⎛⎝⎜⎜⎜⎜⎜⎜131201630537805673968036997322343427464975241039654221213718150111956331⎞⎠⎟⎟⎟⎟⎟⎟

Find the minimal path sum, in matrix.txt (right
click and "Save Link/Target As..."), a 31K text file containing a 80 by 80 matrix, from the top left to the bottom right by moving left, right, up, and down.

首先构造带权有向图,然后用dijkstra方法求解单源最短路径。

ls=[]
for line in open("matrix.txt"):
    #print(line)
    a=line.split(',')
    a=[int(i) for i in a]
    ls.append(a)

maxint=2147483647   
c=[[maxint for j in range (6400)] for i in range(6400)]
dist=[maxint for i in range(6400)]
prev=[maxint for i in range(6400)]

for i in range(0,80):
    for j in range(0,80):
        neighbors=[(i+x,j+y) for x,y in [(-1,0),(0,-1),(1,0),(0,1)] if 0 <= i+x < 80 and 0 <=j+y < 80]
        for ix,jy in neighbors:
            c[i*80+j][ix*80+jy]=ls[ix][jy]

def dijkstra(v):
    s=[0 for i in range(6400)]
    for i in range(0,6400):
        dist[i]=c[v][i]
        if dist[i]==maxint:
            prev[i]=-1
        else:
            prev[i]=v
            
    dist[v]=0
    s[v]=1

    for i in range(0,6399):
        temp=maxint
        u=v
        for j in range(0,6400):
            if s[j]==0 and dist[j] < temp:
                u=j
                temp=dist[j]
        s[u]=1
        for j in range(0,6400):
            if s[j]==0 and c[u][j] < maxint:
                newdist=dist[u]+c[u][j]
                if newdist < dist[j]:
                    dist[j]=newdist
                    prev[j]=u

dijkstra(0)

print(dist[6399])
print('Done')


得到结果420740提交发现不对,然后想到忘记加上路径开始的第一个元素了

420740+4445=425185
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: