I'm new to coding and have not been coding for more than two months. For my assignment, I'm making an escape the maze algorithm. The user defines a 2D array and a start point, then the program must take the least damaging route to find its way out. The "AI" can only move north, east, south, or west. It can escape from any edge of the array.
Enter the starting x coordinate: 2
Enter the starting y coordinate: 4
0 1 4 2 6 0 1
1 7 4 2 2 6 0
0 0 0 8 * 4 1
1 1 2 7 3 4 2
5 1 6 4 2 2 1
In this example, the user has selected [2,4] as the start location of the array (remember, indexing begins at 0). The AI can escape from any edge of the array. It is going to want to pick the smallest integer for each movement. For this example, the AI will move up to 2, then left, then up. Thus it took a sum amount of "6 damage" to exit the array.
My issue is comparing whether North is smaller than East, and if North is smaller than East, is it smaller than West? Or South? If East is smaller than North, is it smaller than West? Or South? & so on and so forth. I'm not sure whether I'm going about this in the correct manner. My attempt can be found at lines 44 - 78 in the hastebin link below. I have no idea what I'm doing.
I created an int minimumValue;
but I'm not sure how to utilize it, or where. If boardArray[north][currentY] < boardArray[east][currentY]
then boardArray[north][currentY]
is my new minimum value correct? Then I would need to write code comparing that to west and south as well. I feel like there has to be a simpler method to go about it.
I've tried googling solutions, Reddit, The Coding Den discord server, but I simply can't get this down.
Any and all help will be appreciated!
Holy nested else's Batman!
I would replace lines 55-78 with something like this:
//find the least danger:
int leastDanger = northDanger;
if(southDanger < leastDanger) leastDanger = southDanger;
if(eastDanger < leastDanger) leastDanger = eastDanger;
if(westDanger < leastDanger) leastDanger = westDanger;
// Go the first direction equal to least danger
if (northDanger == leastDanger) { moveNorth
}else if(southDanger == leastDanger) { moveSouth
}else if(eastDanger == leastDanger) { moveEast
}else if(westDanger == leastDanger) { moveWest
}
The moveDirections would be your code like
visitedPath = visitedPath + "[" + currentX + "," + currentY + "]";
And the danger values are your code like
boardArray[north][currentY]
It could also be done with a switch statement, if you know those.