【发布时间】:2017-05-13 11:30:29
【问题描述】:
我有一个从左上角开始的矩阵(地图)问题,我想找到到右下角较轻的路径。它具有只能向右、向下或向右向下移动的条件。
这是一个例子: matrix example
我需要解决回溯的问题,但我不知道我是否做得很好。
这段代码能够解决最大 10x10 的矩阵大小,但是当我尝试 20x20 的矩阵时,它会卡住(或者至少我在几个小时后是这样认为的)。
/*
* i, j -> matrix iterators.
* n, m -> matrix height and width
* map -> matrix
* actualPath, bestPath -> vectors for representing the path later
* actual -> actual path weight
* best -> best path weight
*/
int backtracking(int i, int j, const int &n, const int &m,
const vector<vector<int>> &map,
vector<vector<int>> &actualPath,
vector<vector<int>> &bestPath,
int best) {
recursiveCalls++;
int actual = 0;
//Bottom-right corner
if(i == (n-1) && j == (m-1)) {
return map[i][j];
}
//Last row, only right
else if(i == (n-1)) {
actual = map[i][j] +
backtracking(i, (j+1), n, m, map, actualPath, bestPath, best, profundidad);
}
//Last column, only down
else if(j == (m-1)) {
actual = map[i][j] +
backtracking((i+1), j, n, m, map, actualPath, bestPath, best, profundidad);
}
else {
int downRight = backtracking((i+1), (j+1), n, m, map, actualPath, bestPath, best, profundidad);
int right = backtracking(i, (j+1), n, m, map, actualPath, bestPath, best, profundidad);
int down = backtracking((i+1), j, n, m, map, actualPath, bestPath, best, profundidad);
actual = map[i][j] + minimo(downRight, right, down);
}
if(actual < best) {
best = actual;
bestPath = actualPath;
}
return best;
}
是否有可能因为我不使用边界而被卡住?还是执行不好? 我不知道我做错了什么。我想我理解这个算法,但我想我不知道如何为这个问题实现它......
【问题讨论】:
-
您是否尝试使用调试器单步执行您的代码?
-
当您说
I need to solve it using backtracking时,这是否意味着虽然您知道回溯可能不是最佳解决方案,但您仍想尝试使用回溯解决它? -
在尝试递归/迭代解决方案时,我总是会在最大递归/迭代次数上设置一个中断条件,这样您至少有机会检查中间解决方案,而不是永远等待跨度>
-
是的,我尝试使用调试器,但它似乎运行良好,至少第一次递归调用...是的,我知道这可能不是最好的解决方案,但我需要解决它回溯。
-
@JDLK7 至少是第一次递归调用,所以很明显错误是在进一步的调用中。继续单步调试代码,直到找到代码开始出现异常的地方。或者另一种可能性:您让代码运行一段时间,然后使用调试器附加到您的代码,以调查当前状态。
标签: c++ algorithm matrix backtracking