本文介绍了刺激基质上的液体流动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须模拟液体流过包含一组整数的方阵.液体应该从矩阵的左上角开始.它只能向相邻矩阵的右侧或下方移动.相邻矩阵的值越低,它流动的潜力就越大.液体的运动被认为停止在矩阵的右边缘或下边缘.程序应该能够显示液体通过的所有数字的总和.

I have to simulate a liquid flow through a square matrix that contains a set of integers. The liquid should start from the top left corner of the matrix. It could only move towards right or below adjacent matrix. The lower value of the adjacent matrix, the higher potential for it to flow. The movement of the liquid is considered stop at the right or below edge of the matrix. The program should be able to show the sum of all numbers that the liquid has passed through.

import numpy as np

mtr= np.array ([[0, 2, 9],
                [4, 9, 8],
                [6, 8, 1]])

print(mtr)

def min_adj_val(a, b):
        if (a < b):
            return a
        else:
            return b

def min_mtr(mtr, m, n):

        if (m == 2 or n == 2):
            return mtr[m][n]
        else:
            return mtr[m][n] + min_adj_val(min_mtr(mtr, m+1, n),min_mtr(mtr, m, n+1))

print(min_mtr(mtr,0, 0))

上面代码的输出:10

预计为:11

我希望按照路径 0-2-9 将其设为 11.但它选择了成本最低的路径,即 0-4-6.我是初学者,刚刚学习编码大约 4 个月.请帮帮我.

I want it to be 11 by following path 0-2-9. But it chooses the lowest cost path which is 0-4-6. I'm beginner and just learn to code about 4 months. Help me, please.

推荐答案

每次调用 min_mtr 都会返回从 (0, 0) 的最短路径>(m, n).当您调用 min_adj_val 时,您的参数是对 min_mtr 的递归调用,这意味着您的所有函数将保持迄今为止看到的最短路径长度并将其添加到当前索引.

Each call to min_mtr will return the shortest length path from (0, 0) to (m, n). When you call min_adj_val, your arguments are recursive calls to min_mtr which means that all your function will do is keep the shortest path length it's seen so far and add it to the current index.

更好的解决方案是编写一个贪婪函数,选择最小相邻索引并将其值添加到运行总数中,一直移动直到到达边界.

A better solution would be to write a greedy function that chooses the min adjacent index and add its value to a running total, moving along until you hit a boundary.

这篇关于刺激基质上的液体流动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 19:59