![](/img/trans.png)
[英]How to calculate a path from [0,0] to [M, N] with min sum in a matrix?
[英]Maximal-score path of length K in a M x N matrix
在處理另一個問題時,我遇到了一個問題:
給定一個矩陣和一個整數k ,在矩陣中找到長度為k的路徑,該路徑將路徑中單元的總和最大化。 該路徑可以在任何單元開始,可以在任何方向進行,並且可以在每個點自由旋轉。 路徑也可以相交,但如果相交,則給定的像元僅對總和計數一次 。
返回總和。
為了解決這個問題,我嘗試了一種遞歸方法,在該方法中,對於每個可能的起始位置(即矩陣的所有元素),我都會計算可能的最長路徑,並嘗試使用查找表,以便在網格中重復某個點產生的值為0。問題是我不確定如何以及何時重新初始化查找表,以免丟失可能的路由。
到目前為止,我的實現看起來像這樣。
int maxP(int i, int j, int steps, int[][] grid) {
if (i < 0 || i >= n || j < 0 || j >= m || steps < 0) {
return 0;
}
// check if place has been passed through before
int cost;
if (lookup[i][j] == 1) {
cost = 0;
} else {
cost = grid[i][j];
lookup[i][j] = 1;
}
return cost + max(
maxP(i - 1, j - 1, steps - 1, grid),
maxP(i - 1, j, steps - 1, grid),
maxP(i - 1, j + 1,steps - 1, grid),
maxP(i, j - 1, steps - 1, grid),
maxP(i, j + 1, steps - 1, grid),
maxP(i + 1, j - 1, steps - 1, grid),
maxP(i + 1, j, steps - 1, grid),
maxP(i + 1, j + 1, steps - 1, grid)
);
}
“如何以及何時重新初始化查找表”的答案是, lookup[i][j]
必須是訪問網格位置的次數的計數。 輸入網格位置時,增加計數。 回溯時,減少計數。 也就是說,您永遠不會“重新初始化查找表” 。 您始終以遞增方式維護表。
修改后的代碼如下所示:
int maxP(int i, int j, int steps, int[][] grid) {
if (i < 0 || i >= n || j < 0 || j >= m || steps < 0) {
return 0;
}
// check if place has been passed through before
int cost = 0;
if (lookup[i][j] == 0) {
cost = grid[i][j];
}
// mark this place as visited
lookup[i][j]++;
// find the best cost recursively
cost = cost + max(
maxP(i - 1, j - 1, steps - 1, grid),
maxP(i - 1, j, steps - 1, grid),
maxP(i - 1, j + 1,steps - 1, grid),
maxP(i, j - 1, steps - 1, grid),
maxP(i, j + 1, steps - 1, grid),
maxP(i + 1, j - 1, steps - 1, grid),
maxP(i + 1, j, steps - 1, grid),
maxP(i + 1, j + 1, steps - 1, grid)
);
// undo the change to the lookup table
lookup[i][j]--;
return cost;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.