Skip to content

Instantly share code, notes, and snippets.

@alexislagante
Created November 11, 2015 07:33
Show Gist options
  • Save alexislagante/1e9bac8a6263aedb9615 to your computer and use it in GitHub Desktop.
Save alexislagante/1e9bac8a6263aedb9615 to your computer and use it in GitHub Desktop.
Maze Solver
var myMaze = [
['f', 'f', 'f', 'f', 'w', 'f', 'f', 'f', 'f', 'f'],
['f', 'f', 'f', 'f', 'w', 'f', 'f', 'w', 'f', 'f'],
['f', 'f', 'w', 'w', 'w', 'f', 'f', 'f', 'f', 'f'],
['w', 'w', 'w', 'f', 'w', 'f', 'f', 'w', 'w', 'f'],
['f', 'f', 'f', 'f', 'w', 'f', 'f', 'w', 'f', 'f'],
['f', 'f', 'f', 'w', 'w', 'e', 'w', 'w', 'w', 'f'],
['f', 'f', 'f', 'f', 'w', 'f', 'w', 'f', 'w', 'f'],
['f', 'f', 'f', 'f', 'w', 'f', 'w', 'f', 'w', 'f'],
['f', 'f', 'f', 'f', 'f', 'f', 'f', 'f', 'w', 'f'],
['f', 'f', 'f', 'f', 'f', 'f', 'f', 'f', 'f', 'f']
];
var allMoves = [];
var cache = {};
function solveMaze(maze, i, j) {
var cacheKey = i+"-"+j;
if (typeof cache[cacheKey] !== 'undefined') {
return cache[cacheKey]
}
if (maze[i][j] == 'e') {
return 0;
} else {
var result = Number.MAX_VALUE;
var moves = getMoves(maze, i, j);
maze[i][j] = 'v';
moves.forEach(function(move) {
result = Math.min(result,solveMaze(maze, move[0], move[1]));
});
result = result+1;
if (result == Number.MAX_VALUE) {
maze[i][j] = 'f';
} else {
maze[i][j] = result;
}
cache[cacheKey] = result;
return result;
}
}
function getMoves(maze, i, j) {
var moves = [];
moves.push([i-1,j]);
moves.push([i,j-1]);
moves.push([i+1,j]);
moves.push([i,j+1]);
return moves.filter(function(cell) {
var i = cell[0];
var j = cell[1];
return (i>=0 && i<maze.length && j>=0 && j<maze[0].length && (maze[i][j]=='f' || maze[i][j]=='e'))
});
}
function printMaze(maze) {
maze.forEach(function (row) {
var line = '';
row.forEach(function(item) {
line = line+' '+item;
})
console.log(line);
});
}
solveMaze(myMaze, 8, 1);
printMaze(myMaze);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment