【发布时间】:2018-04-16 15:56:05
【问题描述】:
我正在尝试在二维数组中找到一条可能的路径,并且我有一个源点 (x,y) 和一个目标点 (destX, destY)。
我正在尝试以回溯递归的方式进行,因为我不关心找到 最短 路径,我只关心找到路径。
问题在于,不知何故,它在算法中直接走到一个角落并卡在那里......所以我想我写了一些不正确的逻辑明智的东西。
递归函数:
$scope.findPath = function(x, y, destX, destY) {
console.log("x: " + x + ", y: " + y);
if(x >= $scope.buttons.length || x < 0 || y >= $scope.buttons[0].length || y < 0) {
return false;
}
if(x == destX && y == destY) {
return true;
}
if(!$scope.checkIfButtonEmpty(x, y)) {
console.log("location not empty")
return false;
}
$scope.solution[x][y].marked = true;
if($scope.findPath(x + 1, y, destX, destY) === true) {
return true;
}
if($scope.findPath(x, y + 1, destX, destY) === true) {
return true;
}
if($scope.findPath(x - 1, y, destX, destY) === true) {
return true;
}
if($scope.findPath(x, y - 1 , destX, destY) === true) {
return true;
}
$scope.solution[x][y].marked = false;
return false;
};
调用递归的函数,在找到路径并将其写入布尔二维数组后,应该以图形方式打印路径:
$scope.startDrawingConnection = function() {
if($scope.startLocation.length == 2 && $scope.endLocation.length == 2){
$scope.findPath($scope.startLocation[0], $scope.startLocation[1], $scope.endLocation[0], $scope.endLocation[1]);
console.log("Finished finding path");
$scope.drawPath();
console.log("Finished drawing path");
}
};
请帮我弄清楚我在算法中做错了什么。
【问题讨论】:
-
$scope.startLocation[0]和$scope.startLocation[1]有没有可能是字符串而不是数字? -
@RickHitchcock 不。我确定问题一般不是来自语法/键入问题,除此之外 $scope.startLocation 是我在代码中定义的一个数组,我没有在这里显示。问题是代码确实运行了,并且递归运行了几次调用,直到它进入一个角落并被困在其中,所以这一定是我在编写递归函数时犯的一个逻辑错误。
标签: javascript angularjs arrays recursion multidimensional-array