JSFiddle - React, Tailwind, and code Playground
HTML
<input type="button" value="New" />
<pre id="original_maze"></pre>
<pre id="steps"></pre>
<pre id="answer"></pre>
JavaScript
$('input[type=button]').click( function() {
mazeSolver();
});
function mazeSolver() {
var maze = [['X','S','X','X','X','X','X'],
['X',' ',' ',' ',' ',' ','X'],
['X',' ','X','X','X','X','X'],
['X',' ',' ',' ',' ',' ','X'],
['X',' ','X','X','X','X','X'],
['X',' ',' ',' ',' ',' ','E'],
['X','X','X','X','X','X','X']];
document.getElementById('original_maze').innerHTML = displayMaze(maze);
var start = findStartEnd(maze,'S');
var end = findStartEnd(maze,'E');
console.log(start);
console.log(end);
fillMaze(maze, start);
document.getElementById('steps').innerHTML = displayMaze(maze);
followSolution(maze, end);
document.getElementById('answer').innerHTML = displayMaze(maze);
}
function followSolution(maze, end) {
var height = maze.length;
var width = maze[0].length;
var cur_step = parseInt( maze[end[0]][end[1]] );
console.log(cur_step)
maze[end[0]][end[1]] = 'o';
while (cur_step > 1) {
y = end[0];
x = end[1];
console.log(end);
console.log(cur_step);
var get_out = 0;
// check each of the neighbours (up down left right)
for(var ny = -1; ny <= 1; ny++) { // If checking all neighbours this could be max(y-1,0):min(y+1,height)
for(var nx = -1; nx <= 1; nx++) {
if (Math.abs(ny) == Math.abs(nx) || y+ny < 0 || y+ny >= height || x+nx < 0 || x+nx >= width )
continue;
if (maze[y+ny][x+nx] == (cur_step-1).toString()) {
end = [y+ny, x+nx];
cur_step = parseInt( maze[end[0]][end[1]] );
maze[y+ny][x+nx] = 'o';
get_out = 1;
break;
}
}
if (get_out == 1)
break;
}
}
}
function...