Project Euler 81:Path sum: two ways 路径和:两个方向
Path sum: two ways
In the 5 by 5 matrix below, the minimal path sum from the top left to the bottom right, by only moving to the right and down, is indicated in bold red and is equal to 2427.
131 | 673 | 234 | 103 | 18 |
201 | 96 | 342 | 965 | 150 |
630 | 803 | 746 | 422 | 111 |
537 | 699 | 497 | 121 | 956 |
805 | 732 | 524 | 37 | 331 |
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 only moving right and down.
在如下的5乘5矩阵中,从左上方到右下方始终只向右或向下移动的最小路径和为2427,由标注红色的路径给出。
131 | 673 | 234 | 103 | 18 |
201 | 96 | 342 | 965 | 150 |
630 | 803 | 746 | 422 | 111 |
537 | 699 | 497 | 121 | 956 |
805 | 732 | 524 | 37 | 331 |
在这个31K的文本文件matrix.txt(右击并选择“目标另存为……”)中包含了一个80乘80的矩阵,求出从该矩阵的左上方到右下方始终只向右和向下移动的最小路径和。
解题
这个题目很简单的
对第0列和第0行的数直接向下加
第0列:data[i][0] = data[i][0] + data[i-1][0] for i in 1:row - 1
第0行: data[0][i] = data[0][i] + data[0][i-1] for i in 1:col-1
其他情况
for i in 1:row -1
for j in 1:col-1
data[i][j] = data[i][j] + min(data[i-1][j],data[i][j-1])
最后元素data[row-1][col-1]就是最小路径的值。
Python
import time ;
import numpy as np def run():
filename = 'E:/java/projecteuler/src/Level3/p081_matrix.txt'
data = readData(filename)
Path_Sum(data) def Path_Sum(data):
row,col = np.shape(data)
for i in range(1,row):
data[0][i] = data[0][i]+data[0][i-1]
data[i][0] = data[i][0] + data[i-1][0]
for i in range(1,row):
for j in range(1,col):
data[i][j] += min(data[i-1][j],data[i][j-1])
print data[row-1][col-1] def readData(filename):
fl = open(filename)
data =[]
for row in fl:
row = row.split(',')
line = [int(i) for i in row]
data.append(line)
return data
if __name__=='__main__':
t0 = time.time()
run()
t1 = time.time()
print "running time=",(t1-t0),"s" #
# running time= 0.00799989700317 s
参考博客中的读取文件,这个读取文件的思想很好的,自己对于读取文件还不是很熟悉
上个Python程序是按照左上到右下走的
下面java的是按照右下向左上走的
package Level3; import java.awt.List;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList; public class PE081{ static int[][] grid;
static void run() throws IOException{
String filename = "src/Level3/p081_matrix.txt";
String lineString = "";
ArrayList<String> listData = new ArrayList<String>();
BufferedReader data = new BufferedReader(new FileReader(filename));
while((lineString = data.readLine())!= null){
listData.add(lineString);
}
// 分配大小空间的 定义的grid 没有定义大小
assignArray(listData.size());
// 按照行添加到数组grid中
for(int index = 0,row_counter=0;index <=listData.size() - 1;++index,row_counter++){
populateArray(listData.get(index),row_counter);
}
System.out.println(Path_min(grid)); }
public static int Path_min(int[][] data){
int size = data.length;
for(int i=size -2;i>=0;--i){
data[i][size-1] += data[i+1][size-1];
data[size-1][i] += data[size-1][i+1];
}
for( int index = size -2;index >=0;index--){
for(int innerIndex = size -2;innerIndex >=0;innerIndex--){
data[index][innerIndex] += Math.min(data[index+1][innerIndex],
data[index][innerIndex+1]);
}
}
return data[0][0];
}
// 每行的数据添加到数组中
public static void populateArray(String str,int row){
int counter = 0;
String[] data = str.split(",");
for(int index = 0;index<=data.length -1;++index){
grid[row][counter++] = Integer.parseInt(data[index]);
}
}
public static void assignArray(int no_of_row){
grid = new int[no_of_row][no_of_row];
} public static void main(String[] args) throws IOException{
long t0 = System.currentTimeMillis();
run();
long t1 = System.currentTimeMillis();
long t = t1 - t0;
System.out.println("running time="+t/1000+"s"+t%1000+"ms");
// 427337
// running time=0s38ms
}
}
Project Euler 81:Path sum: two ways 路径和:两个方向的更多相关文章
- Project Euler 83:Path sum: four ways 路径和:4个方向
Path sum: four ways NOTE: This problem is a significantly more challenging version of Problem 81. In ...
- Project Euler 82:Path sum: three ways 路径和:3个方向
Path sum: three ways NOTE: This problem is a more challenging version of Problem 81. The minimal pat ...
- Leetcode 931. Minimum falling path sum 最小下降路径和(动态规划)
Leetcode 931. Minimum falling path sum 最小下降路径和(动态规划) 题目描述 已知一个正方形二维数组A,我们想找到一条最小下降路径的和 所谓下降路径是指,从一行到 ...
- 【LeetCode-面试算法经典-Java实现】【064-Minimum Path Sum(最小路径和)】
[064-Minimum Path Sum(最小路径和)] [LeetCode-面试算法经典-Java实现][全部题目文件夹索引] 原题 Given a m x n grid filled with ...
- [LeetCode] Path Sum II 二叉树路径之和之二
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given su ...
- [LeetCode] Path Sum 二叉树的路径和
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all ...
- [LeetCode] Binary Tree Maximum Path Sum(最大路径和)
Given a binary tree, find the maximum path sum. The path may start and end at any node in the tree. ...
- [LeetCode] 113. Path Sum II 二叉树路径之和之二
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given su ...
- [LeetCode] 112. Path Sum 二叉树的路径和
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all ...
随机推荐
- Android关于buildToolVersion与CompileSdkVersion的区别
StackOverFlow中对这个问题进行了详细的讨论:http://stackoverflow.com/questions/24521017/android-gradle-buildtoolsver ...
- Error LNK2005 从敌人到朋友
本人在写学生信息管理系统时遇到一个很头疼的错误——error LNK2005重复定义错误,苦思冥想百度谷歌bing之后都没能解决问题,于一清早刹那间觉得知道问题出在哪儿了,于是乎起床.开机.修改代码一 ...
- 括弧匹配检验(check)
/*题目:括弧匹配检验 检验给定表达式中括弧是否正确匹配 (两种括弧“( ) ”“[]" ,正确输出OK,错误则输出wrong. 2016年8月8日07:24:58 作者:冰樱梦 */ # ...
- MySQL ibdata1撑爆占满磁盘空间
MySQL主从由于ibdata1占满磁盘空间-->主从失效 因为设置了innodb_file_per_table = 1,ibdata1依旧撑爆占满磁盘空间 主从断的时候,IO线程在连接,SQL ...
- elipse+pydev+python开发arcgis脚本程序
环境配置参考:http://www.cnblogs.com/halfacre/archive/2012/07/22/2603848.html 添加arcpy类库.arctoolbox.arcgis-b ...
- MS MQ 消息队列
一.安装 先在 控制面板—程序和功能—打开或关闭我windows功能.把 msmq全勾起来 如下图: 二.右击-消息对列—属性—服务器安全性,把禁用未经身份验证的RPC调用勾去掉, 三.然后在专用队列 ...
- 将eclipse的应用程序打包成.exe
转自:http://blog.163.com/loveshijie_1991/blog/static/1760553112012102573437156/ 参考:http://blog.csdn.ne ...
- linux 命令grep
linux 命令grep grep命令用来搜索文本,或从给定的文件中搜索行内包含了给定字符串或单词的文件.通常来说,grep显示匹配的行.使用grep来搜索包括一个或多个正则表达式匹配到的文本行,然后 ...
- Export Farm Solution wsp Files SharePoint 2007 and 2010
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")$farm = [Microsof ...
- cocos2dx中的内存管理机制及引用计数
1.内存管理的两大策略: 谁申请,谁释放原则(类似于,谁污染了内存,最后由谁来清理内存)--------->适用于过程性函数 引用计数原则(创建时,引用数为1,每引用一次,计数加1,调用结束时, ...