Stimulating Liquid Flow on Matrix

放肆的年华 提交于 2021-01-29 06:50:31

问题


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)) 

Output of code above : 10

Expected to be: 11

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.


回答1:


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.



来源:https://stackoverflow.com/questions/63116699/stimulating-liquid-flow-on-matrix

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!