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方法求解单源最短路径。
得到结果420740提交发现不对,然后想到忘记加上路径开始的第一个元素了
420740+4445=425185
⎛⎝⎜⎜⎜⎜⎜⎜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
相关文章推荐
- linux下查看用户和组的详细信息
- tomcat 一种简单使用方式!
- swif关于ios生命管理周期
- 正则表达式基本语法介绍
- Eclipse JNI实现头文件报错:parameter name omitted
- LeetCode(31) Next Permutation
- U_BOOT移植
- Openssl dgst命令
- 贝叶斯决策
- Redis命令小细节
- oc004---oc的继承
- 【POJ】【3624】
- Java 位运算符 深入理解
- Maven实战(Maven框架概览)
- Palindrome Linked List
- Socket编程《三》
- IOS--UI--LessonParse 数据解析 XML JSON
- STL--关于权重问题的解决
- EventBus使用详解
- 动画中的id与class使用css3的优先级问题