Path sum: three ways

NOTE: This problem is a more challenging version of Problem 81.

The minimal path sum in the 5 by 5 matrix below, by starting in any cell in the left column and finishing in any cell in the right column, and only moving up, down, and right, is indicated in red and bold; the sum is equal to 994.

         
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 left column to the right column.


路径和:三个方向

注意:这是第81题的一个更具挑战性的版本。

在如下的5乘5矩阵中,从最左栏任意一格出发,始终只向右、向上或向下移动,到最右栏任意一格结束的最小路径和为994,由标注红色的路径给出。

         
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的矩阵,求出从最左栏到最右栏的最小路径和。

 解题

第一反应是不知如何下手,上一题那种类型的见过好多,立马知道怎么做了

参考博客1  参考博客2

先举个例子说明

(0,0) (0,1) (0,2) (0,3) (0,4)
(1,0) (1,1) (1,2) (1,3) (1,4)
(2,0) (2,1) (2,2) (2,3) (2,4)
(3,0) (3,1) (3,2) (3,3) (3,4)
(4,0) (4,1) (4,2) (4,3) (4,4)

如上图的4x4的矩阵

定义ans数组:ans数组是矩阵最后一列的元素值,长度是5,如:ans[0] = A[0,4],ans[1]=A[1,4] ,ans[2]=A[2,4],ans[3]=A[3,4],ans[4]=A[4,4]

ans[i]表示的是走到i行时候的最小路径,这里隐藏了列的信息,ans是变换的

从最后一列开始,向前一列”走“,这里的走包括直接左走和经过上或者下走的的结果。我们要求的是所走的路径的最小值。

先考虑向下走和直接左走的情况:

走到A[0,3],只有从A[0,4]直接左走,ans[0] = ans[0] + A[0,3]

走到A[1,3],其走的最小值应该是:ans[1] = MIN(ans[0]+A[1,3],ans[1]+A[1,3]),一个是经过A[0,3]到达A[1,3] 一个是直接左走

走到A[2,3],其走的最小值应该是: ans[2] = MIN(ans[1]+A[2,3],ans[2] +A[1,3]),一个是走到A[1,3]的最小路径再走到A[2,3],一个是前一个最小路径直接左走过来的

走到A[3,3],  其走的最小值应该是:ans[3] = MIN(ans[2]+A[3,3],ans[3] +A[3,3]),一个是走到A[2,3]的最小路径再走到A[2,4],一个是前一个最小路径直接左走过来的

同理

ans[4] = MIN(ans[3]+A[4,3],ans[4]+A[4,3])

对于向上走的情况

我们要从A[4,3]开始向上走,主要这里的直接向左走的上面已经走了,只需要考虑向上走的和上面走的结果的最小值即可

走到A[3,3],走的最小值应该是:ans[3] = MIN(ans[3],ans[4]+A[3,3]) 一个是下左走的最小值,一个是下面节点向上走的最小值+当前节点的值

走到A[2,3],走的最小值应该是:ans[2] = MIN(ans[2],ans[3]+A[2,3])

走到A[1,3],走的最小值应该是:ans[1] = MIN(ans[1],ans[2]+A[1,3])

走到A[0,3],走的最小值应该是:ans[0] = MIN(ans[0],ans[1]+A[0,3])

这样从最后一列,慢慢的向前走,走到了前一列,ans的值全部更新,继续走,当走到最后的时候,ans中的最小值就是最小路径。注意:ans[i]始终是保存的走到行某列时候的最小值

Java

package Level3;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList; public class PE082{ static int[][] grid;
static void run() throws IOException{
String filename = "src/Level3/p082_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;
int ans[] = new int[size];
for(int i =0;i<size;i++)
ans[i] = data[i][size-1];
// 最后一类的前一个路径一定是同行的前一列
for(int index = size -2;index>=0;index--){
ans[0] += data[0][index];
// 向下
for(int innerIndex = 1;innerIndex<size;innerIndex++){
ans[innerIndex] = Math.min(ans[innerIndex]+data[innerIndex][index],
ans[innerIndex-1]+data[innerIndex][index]);
}
// 向上
for(int innerIndex = size-2;innerIndex>=0;innerIndex--){
ans[innerIndex] = Math.min(ans[innerIndex],
ans[innerIndex+1]+data[innerIndex][index]);
}
}
int MIN = Integer.MAX_VALUE;
for(int i = 0;i<size;i++)
if(MIN>ans[i])
MIN = ans[i];
return MIN;
}
// 每行的数据添加到数组中
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");
// 260324
// running time=0s31ms
}
}

Java Code

Python

import time ;
import numpy as np def run():
filename = 'E:/java/projecteuler/src/Level3/p082_matrix.txt'
data = readData(filename)
Path_Sum(data) def Path_Sum(data):
size,size = np.shape(data)
ans = [data[i][size-1] for i in range(size)]
for i in range(size-2,-1,-1):
ans[0] = ans[0] + data[0][i]
for j in range(1,size):
ans[j] = min(ans[j]+data[j][i],ans[j-1]+data[j][i])
for j in range(size-2,-1,-1):
ans[j] = min(ans[j],ans[j+1]+data[j][i])
print min(ans) 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.0150001049042 s

Python Code

在上面的求解过程中,好像和三角数求最小路径的过程很相似,这里给的是个矩阵,会有很多三角形。哦哦哦哦,用三角形最小路径解题很复杂。。。首先要保存原始矩阵数据,就没有其次了。

Project Euler 82:Path sum: three ways 路径和:3个方向的更多相关文章

  1. 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 ...

  2. 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 ...

  3. Leetcode 931. Minimum falling path sum 最小下降路径和(动态规划)

    Leetcode 931. Minimum falling path sum 最小下降路径和(动态规划) 题目描述 已知一个正方形二维数组A,我们想找到一条最小下降路径的和 所谓下降路径是指,从一行到 ...

  4. 【LeetCode-面试算法经典-Java实现】【064-Minimum Path Sum(最小路径和)】

    [064-Minimum Path Sum(最小路径和)] [LeetCode-面试算法经典-Java实现][全部题目文件夹索引] 原题 Given a m x n grid filled with ...

  5. [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 ...

  6. [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 ...

  7. [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. ...

  8. [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 ...

  9. [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 ...

随机推荐

  1. Jexus 高并发请求的优化技巧 笔记

    Jexus web server 5.1 每个工作进程的最大并发数固定为1万,最多可以同时开启4个工作进程,因此,每台Jexus V5.1服务器最多可以到支持4万个并发连接.但是,按照linux系统的 ...

  2. 30个HTML5学习资源

    早在几个星期前,Adobe就发布了Dreamweaver CS5 HTML5 Pack的预览版下载.众所周知,HTML5在互联网领域掀起了一场大论战,并让Adobe的日子很难熬.HTML5致力于为前端 ...

  3. maven 相关

    maven相关 一 windows安装配置maven: 1. 官网下载最新版本maven,发布日志时为: maven3.2.1 2.解压maven到相应的目录:配置环境变量: MAVEN_HOME:D ...

  4. Win10环境下的Scrapy结合Tor进行匿名爬取

    本文内容来源:http://blog.privatenode.in/torifying-scrapy-project-on-ubuntu/ 在使用Scrapy的时候,一旦进行高频率的爬取就容易被封IP ...

  5. WPF之旅(三)- 布局之StackPanel

    说到WPF的界面布局,相信很多朋友都写过Html代码.在WPF中,大多数程序都使用类似Web的(flow)流布局.在使用流布局模型时,各种控件可以按特定的要求来排列,在窗口内容发生变化时,比如窗口大小 ...

  6. C#TCPClient应用-一个简单的消息发送和接收

    TcpSend窗口用于发送消息,另外写一个用于接收消息的应用程序,消息接受到以后,必须要关闭接收消息的窗口,才能在接收新的消息,不知道怎么能解决这个问题. 源代码: 发送消息的窗口代码 using S ...

  7. IOS 控件的生命周期

    ViewController的生命周期包括: Initialize ViewDidLoad ViewWillAppear ViewDidAppear ViewWillDisappear ViewDid ...

  8. 从零开始学ios开发(十五):Navigation Controllers and Table Views(中)

    这篇内容我们继续上一篇的例子接着做下去,为其再添加3个table view的例子,有了之前的基础,学习下面的例子会变得很简单,很多东西都是举一反三,稍稍有些不同的内容,好了,闲话少说,开始这次的学习. ...

  9. Newtonsoft.Json同时对多个时间字段以不同的格式序列化

    在博客园潜水多年,学到很多,也进步了很多,在这里说声谢谢,是时候给园友分享一点自己的东西,希望和大家一起进步. 之前有个需求要对一张表的多个时间字段进行不同的格式序列化, 在网上没找到相对较好的解决方 ...

  10. 【BZOJ 2245】[SDOI2011]工作安排

    Description 你的公司接到了一批订单.订单要求你的公司提供n类产品,产品被编号为1~n,其中第i类产品共需要Ci件.公司共有m名员工,员工被编号为1~m员工能够制造的产品种类有所区别.一件产 ...