Created
November 11, 2015 07:33
-
-
Save alexislagante/1e9bac8a6263aedb9615 to your computer and use it in GitHub Desktop.
Maze Solver
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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