刺激基質上的液體流動 (Stimulating Liquid Flow on Matrix)


問題描述

刺激基質上的液體流動 (Stimulating Liquid Flow on Matrix)

我必須模擬通過包含一組整數的方陣的液體流動。液體應該從矩陣的左上角開始。它只能向相鄰矩陣的右側或下方移動。相鄰矩陣的值越低,它流動的可能性就越大。液體的運動被認為是在矩陣的右邊緣或下邊緣停止。該程序應該能夠顯示液體通過的所有數字的總和。

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

我希望它是 11,按照路徑 0‑2‑9。但它選擇了成本最低的路徑,即 0‑4‑6。我是初學者,剛學會編碼大約 4 個月。請幫幫我。


參考解法

方法 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.

(by VaneswaranKuzminK13)

參考文件

  1. Stimulating Liquid Flow on Matrix (CC BY‑SA 2.5/3.0/4.0)

#matrix #Python #path






相關問題

BLAS 子程序 dgemm、dgemv 和 ddot 不適用於標量? (BLAS subroutines dgemm, dgemv and ddot doesn't work with scalars?)

為什麼我們需要維護自己的矩陣來轉換遊戲對象? (Why we need to maintain our own matrices to transform Game objects?)

R 高斯消除和 qr 分解 (R Gaussian Elimination and qr factorization)

生成尺寸為 8x8 的正定矩陣 (Generating Positive definite matrix of dimensions 8x8)

替代在此 Ruby 代碼中使用基於時間間隔分配標籤的巨型 if/else (Alternative to using a giant if/else in this Ruby code that assigns labels based on the time interval)

如何創建一個行矩陣,其元素是我的 while 循環的迭代 (How to create a row matrix whose elements are the iterations of my while loop)

在Matlab中找到矩陣中相同元素的開始索引和結束索引 (Find the Start Index and End Index of the same Element in a Matrix in Matlab)

用 Matlab 寫一個方程(矩陣大小) (writing an equation with Matlab (Matrix size))

使用 numpy 或 pandas 從元組列表中為二元組創建頻率矩陣 (Create a frequency matrix for bigrams from a list of tuples, using numpy or pandas)

如何在循環和 if 語句中使用遞歸公式 (How to use recursive formula in loop and if statement)

如何從 p 值矩陣中獲得緊湊的字母顯示? (How to get a compact letter display from a matrix of p-values?)

刺激基質上的液體流動 (Stimulating Liquid Flow on Matrix)







留言討論