I am attempting to navigate a 2D array from a starting point (x,y) to a destination point (destX, destY).
My approach involves utilizing backtracking recursion to find any possible path instead of focusing on the shortest one.
However, I have encountered an issue where the algorithm seems to get trapped in a corner, indicating a flaw in my logic somewhere.
Here is the recursive function:
$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;
};
The following function initiates the recursion and once a path is found and stored in a boolean 2D array, it is meant to visually display the path:
$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");
}
};
I am seeking assistance in identifying the error in my algorithm. Any help would be greatly appreciated.