There are many standard path finding algorithms that you could use to do this.
It is not related to javascript.
You can use one algorithm without heuristics, and you should not stop on the first decision.
Here's how you can do it:
The trick is that you need to save the already visited squares in the list and check if you are reviewing one of them at every step.
Another trick - you need a certain order between adjacent squares. (Like top / right / bottom / left. This is a really stupid algorithm, but great for this particular case.)
You should also be able to identify the squares (this is possible by its position)
Consider a recursive function (e.g. name it Visit):
function visit(square) { add the square to the pathlist //pathlist is not a list of paths but a list of squares which is the current path if (square is the goal) { add a copy of the pathlist to the goalslist } else { for (each adjacency in square.adjacencies) { // this can be calculated by adding +1 and -1 to the coordinates, and checking if its overflowing (less then one/more than five) if (adjacency is in pathlist) { //do nothing we have already been here } else { visit(adjacency) } } } remove square from the pathlist!! }
Run this algorithm by visiting (start). You get your result in goallist, which we hope is a list of paths.
It is also only half the javascript-half pseudocode, but it is easy to write javascript from it.
EDIT: Enjoy the solution:
<script type="text/javascript"> var start = [1,1], goal = [5,5], pathList = [], solutionList = [], solutionCount = 0, width = 5, height = 5; function squareInArray(square, array) { var i = 0, x = square[0], y = square[1]; for (i = 0; i < array.length; i++) { if (x == array[i][0] && y == array[i][1]) { return true; } } return false; } function visit(square) { var i = 0, x = square[0], y = square[1], adjacencies = [[x-1,y],[x+1,y],[x,y+1],[x,y-1]]; pathList.push(square); if (x == goal[0] && y == goal[1]) { var solution = pathList.slice(0); width || adjacencies[i][1] < 1 ||adjacencies[i][1] > height) { //overflow } else { if (squareInArray(adjacencies[i], pathList)) { //do nothing we have already been here } else { visit(adjacencies[i]); } } } } pathList.pop(); } visit(start); alert(solutionCount); </script>
8512 goals. Also someone should check if my code is correct.
Check out this script: http://jsfiddle.net/SoonDead/rd2GN/3/