该程序用于找出矩阵中两点之间的最短路径, 其中我向下,向右,向左和向上移动,但由于递归,它会进入一个来回的无限循环。
这个程序基本上遍历矩阵
问题是找到B和C之间最短的浴槽。
我怎样才能使这段代码工作?如同在一次之后停止控制下降。
if (seconds == 0) {
clearInterval(myVar);
// add activity
}
答案 0 :(得分:0)
只需使用“D”标记您访问过的每个字段,以避免返回。所以在shortestPath
中,在调用checkFeasibility
之后,在检查值是否为'C'之后,执行以下操作:
a[bx][by] = 'D';
答案 1 :(得分:0)
详细阐述Frank Puffer的想法:
class Stockroom {
public static boolean checkFeasibility(int x, int y, int row, int col,
char a[][]) {
if (x >= 0 && x < row && y >= 0 && y < col && a[x][y] != 'D')
return true;
else
return false;
}
public static boolean shortestPath(char a[][], int bx, int by, int x,
int y, int len, int minLen) {
if (checkFeasibility(bx, by, x, y, a) == false)
return false;
if (a[bx][by] == 'C') {
minLen = Math.min(len, minLen);
System.out.println(minLen - 1);
return true;
}
len++;
if (len >= minLen) { // this was not shortest
return false;
}
// hack to make sure we don’t go through the same spot again
a[bx][by] = 'D';
if (shortestPath(a, bx + 1, by, x, y, len, minLen) == true) {
// remove temporary block so this space can be used in other paths
a[bx][by] = '_';
return true;
}
if (shortestPath(a, bx, by + 1, x, y, len, minLen) == true) {
a[bx][by] = '_';
return true;
}
if (shortestPath(a, bx, by - 1, x, y, len, minLen) == true) {
a[bx][by] = '_';
return true;
}
if (shortestPath(a, bx - 1, by, x, y, len, minLen) == true) {
a[bx][by] = '_';
return true;
}
len--;
return false;
}
public static void main(String[] args) {
// find path from B to C; don’t go through D
char arr[][] = { { '_', 'B', '_', '_' },
{ 'D', '_', '_', 'D' },
{ '_', 'D', '_', '_' },
{ '_', '_', 'C', '_' },
};
int bx = 0, by = 1, px = 3, py = 2;
int n = 4, m = 4;
shortestPath(arr, bx, by, m, n, 0, 100);
System.out.println(Arrays.deepToString(arr));
}
}
这可以修复&#39; _&#39;字段,但仍覆盖&#39; B&#39;。程序打印3,因为最短路径长度为4,您减去1。