由于您的描述性不够好,我将尽力解释基本概念。
1) 检查当前坐标是否达到目标,返回当前总和。这是基本情况。
2) 检查当前采取的步数是否超过防止无限递归所需的最大步数。这是失败的情况,在使用广度优先搜索时是必需的。
3) 检查您要步行到的下一个所需位置是否在网格内,并且之前未被访问过。将其标记为已访问并保存该路径的总和。当您返回时,将该位置标记为未访问并尝试下一个可用的移动......等等所有可能的方向。
4) 在尝试了所有可能的路径后,比较它们的结果,看看哪个是最小的,并将其作为解决方案返回。
使用深度优先递归的示例:
public void solve(int[][] a, boolean[][] visited, int sum, int steps, int x, int y, int xMax, int yMax) {
if (isSolved(x, y)) { // Base case - solved
return sum;
}
if (steps > MAX_STEPS) {
return Integer.MAX_VALUE; // Return invalid if the algorithm exceeds maximum steps to prevent unlimited seek time
}
int[] path = new int[NUM_PATHS]; // An array holding the calculated paths for all possible options. Should
for (int i = 0; i < NUM_PATHS; i++) {
path[i] = Integer.MAX_VALUE; // Should be set to fail case as default.
}
if (canReach(x + 1, y) && !visited[y][x +1]) {
visited[y][x + 1] = true;
path[0] = solve(a, visited, sum + a[y][x + 1] steps + 1, x + 1, y, xMax, yMax);
visited[y][x + 1] false;
}
if (canReach(x - 1, y) && !visited[y][x - 1]) {
...
}
... etc
// Finding the best solution
min = path[0];
for (int i = 1; i < path.length; i++) {
if (path[i] < min)
min = path[i];
}
return min;
}
使用动态编程,您可以优化算法以忽略比之前找到的最佳路径更差的路径,从而缩短所需的递归。
此外,如果您想保存所采用的路径,您可以通过 ArrayList 执行此操作,并像将节点标记为已访问时一样添加/删除它。