【问题标题】:Backtracking recursion to find a path from source to destination in 2D array回溯递归以在二维数组中查找从源到目的地的路径
【发布时间】: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


【解决方案1】:

问题是你会绕圈子,访问你之前已经尝试过的节点(没有成功),然后再试一次。

搜索永远不必访问同一个广场两次。所以要跟踪你以前去过的地方,这样你就不会在回溯时抹去那个痕迹,也不会再从那个方格开始搜索。

您可以通过在解决方案节点中添加一个附加属性来实现这一点,并在使用marked = true 标记节点之前添加这两行代码:

    if ($scope.solution[x][y].visited) return false;
    $scope.solution[x][y].visited = true;

【讨论】:

  • 非常感谢您提供的简单解决方案!我以前试过,但我猜我写这些行的顺序和位置使它不起作用。现在,如果我想找到最短路径,有没有办法重构我已经编写的代码,或者我必须使用 Bellman Ford、Dijkstra 等算法编写一个全新的解决方案?
  • 如果您想找到最短路径,DFS 并不是最有效的。在目标仅一步之遥的极端情况下,DFS 搜索可能会在意识到它就在那里之前访问整个网格。所以,是的,你会寻找基于 BFS 的算法。例如,您可以查看my answer here
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-22
  • 2019-07-10
  • 1970-01-01
  • 2012-09-04
  • 1970-01-01
  • 2021-08-26
相关资源
最近更新 更多